#! /bin/sh
#
# Copyright 1997-2000 Microsoft Corporation -- All Rights Reserved.
#
# $Revision: 1.30 $
# $Date: 2000/04/06 $
#

banner()
{
cat <<EOF


 change_server.sh

 Revision$Revision: 1.30 $dummy
 Date$Date: 2000/04/06 $dummy

This script will step the user through upgrading existing and installing 
new servers and webs.  As with any software installation, a backup should be
done before continuing.  It is recommended that the FrontPage installation
directory, server configuration file directory, and all web content be 
backed up before continuing with this installation.

EOF

 myprompt 'yYnN' "Are you satisfied with your backup of the system (y/n)" "N"
 if [ $answer = n ] || [ $answer = N ]
 then
    exit 0
 fi
 echo
 
 return 0
}

initialize()
{
  VERSION="4.0"
  PATH=".:/bin:/usr/bin:/sbin:/usr/sbin:/usr/ucb:/etc:/usr/bsd"
  NEWHTTPDNEW="/usr/local/frontpage/version${VERSION}/apache-fp/httpd"
  NEWHTTPDCOMPAT="/usr/local/frontpage/version${VERSION}/apache-fp/httpd.Compat"
  DEFAULTHTTPD="/usr/local/apache/sbin/httpd"

case "`echo 'x\c'`" in
   'x\c')   echo="echo -n"    nnl= ;;      #BSD
   x)       echo="echo"       nnl="\c" ;;  # Sys V
   *)       echo "$0 quitting:  Can't set up echo." ; exit 1 ;;
esac

 TAB="	"
 system=`uname -a`

 case "$system" in
     OSF1*)            machine="alpha" ;;
     Linux*mips*)      machine="mips-linux" ;;
     Linux*)           machine="linux" ;;
     HP-UX*)           machine="hp700" ;;
     AIX*)             machine="rs6000" ;;
     IRIX*)            machine="sgi" ;;
     SunOS*5.*sun4*)   machine="solaris" ;;
     SunOS*5.*i386*)   machine="solarisx86" ;;
     BSD/OS*)          machine="bsdi" ;;
     SCO_SV*)          machine="sco5" ;;
     FreeBSD*)         machine="freebsd" ;;
     UnixWare\ *\ *\ 7*\ i*) machine="uware7" ;;
     *)                echo "ERROR:  Unsupported platform!  Uname is $system." 
                       return 1
                       ;;
 esac

 case "$machine" in 
   sunos) functions="function toupper(CHAR) {
                     UPPER = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";
                     LOWER = \"abcdefghijklmnopqrstuvwxyz\";
                     if (POS = index(LOWER,CHAR))
                         RETVAL = substr(UPPER,POS,1);
                     else 
                         RETVAL = CHAR;

                     return RETVAL 

                     }

                     function tolower(CHAR) {
                     UPPER = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";
                     LOWER = \"abcdefghijklmnopqrstuvwxyz\";
                     if (POS = index(UPPER,CHAR))
                        RETVAL = substr(LOWER,POS,1);
                     else 
                        RETVAL = CHAR;

                     return RETVAL 

                     }"
          ;;
       *) functions="" 
          ;;
 esac    

 awk=nawk
 lsg="ls -ld"
 psea="ps -ea"
 fgrep=fgrep
 strings=cat 
 whoami=whoami
 
 case "$machine" in
         linux) awk=awk
                psea="ps ea"
                ;;
         bsdi) awk=awk
                ;;
         freebsd) awk=awk
                ;;
         mips-linux) awk=awk
                psea="ps ea"
                ;;
         hp700) awk=awk
                ;;
         alpha) strings="strings -a"
                ;;
         sco5) strings="strings -a"
               whoami=/usr/bin/id
                ;;
         rs6000) strings="strings -a"
                ;;
         *) 
                ;;
 esac

}

checkuser()
{
 #
 # Make sure we are running as root.
 #

 echo "Checking user environment..."
 whoiam=`$whoami | sed -e ' s/).*//; s/^.*(//;'`
 retval=0
 
 if [ $whoiam != "root" ]
 then
    echo "ERROR:  Logged in as $whoiam.  Must be root to do this installation!"
    return 1
 else
    echo "Logged in as root." 
 fi

 echo "Setting umask to 002" 
 umask 002

 return $retval

}

myprompt()
{
 answer="|"
 until echo $1 | grep $answer >/dev/null
 do
    $echo "${2} [${3}]?  ${nnl}" 
    read answer
    if [ "$3" != "" ] && [ "$answer" = "" ]
    then
       answer=$3
    fi
 done
}

InstallFPexe()
{

 checkPermissions ||
 {
     echo
     echo "ERROR:  Unable to chown/chmod extensions!"
     return 1
 }

 httpdfile=""
 while ( [ "$httpdfile" = "" ] || [ ! -x $httpdfile ] )
 do
     httpdfile=$DEFAULTHTTPD
     $echo "Where is the current apache daemon located:  [$httpdfile] ${nnl}"
     read location
     if [ "$location" != "" ]
     then
        httpdfile=$location
     fi
 done

 checkVersion
 rtc=$?
 if [ $rtc -eq 1 ]
 then
     exit 0
 elif [ $rtc -eq 2 ]
 then
     return 0
 fi 

 upgradeServer || 
 {
     echo "ERROR:  Unable to upgrade Apache daemon!"
     return 1
 }

 return 0
}

checkVersion()
{
 rtc=0;

 clear


 if ($strings $httpdfile | $fgrep "etc/httpd.conf" > /dev/null)
 then
    NEWHTTPD=$NEWHTTPDNEW
    echo "Selected server uses NEW directory structure:"
 else
    NEWHTTPD=$NEWHTTPDCOMPAT
    echo "Selected server uses COMPATIBLE directory structure:"
 fi

 echo "$NEWHTTPD will be installed."

 targetVersionNumber=`$httpdfile -v | sed 's%^.*Apache/\([0-9\.]*\).*%\1%' | head -1`
 targetFPVersionNumber=`$strings $httpdfile | $fgrep "FrontPage/" 2> /dev/null | sed -e '
                              s%^.*FrontPage/\([0-9\.]*\).*%\1%' | tail -1`
 sourceVersionNumber=`$NEWHTTPD -v | sed 's%^.*Apache/\([0-9\.]*\).*%\1%' | head -1`
 sourceFPVersionNumber=`$strings $NEWHTTPD | $fgrep "FrontPage/" 2> /dev/null | sed -e '
                              s%^.*FrontPage/\([0-9\.]*\).*%\1%' | tail -1`
            
 echo
 echo "Currently running Apache/${targetVersionNumber} FrontPage/${nnl}" 
 if [ "${targetFPVersionNumber}" = "" ]
 then
    echo "No Patch."
    FPCompare=GT
 else
    echo "${targetFPVersionNumber}."
    compareVersions $sourceFPVersionNumber $targetFPVersionNumber FPCompare
 fi
 echo
 echo "Preparing for upgrade to Apache/${sourceVersionNumber} FrontPage/${sourceFPVersionNumber}..."
 echo

 compareVersions $sourceVersionNumber $targetVersionNumber ApacheCompare

 if [ "${ApacheCompare}" = "EQ" -a "${FPCompare}" = "EQ" ]
 then
    echo
    echo "The Apache daemon seems to have already been upgraded."
    rtc=2    
 else
    echo 
    echo "The Apache daemon is going to be replaced with a stock Apache"
    echo "containing the FrontPage patch and may result in the loss of"
    echo "any custom modules that have been compiled into the daemon that"
    echo "is currently in use."
    echo
    myprompt 'yYnN' "Are you sure that you want to do this (y/n)" "N"
    if [ $answer = n ] || [ $answer = N ]
    then
       rtc=1
    elif [ "${ApacheCompare}" = "LT" ] 
    then
       echo "This will result in an Apache daemon version downgrade."
       echo
       myprompt 'yYnN' "Are you sure that you want to do this (y/n)" "N"
       if [ $answer = n ] || [ $answer = N ]
       then
          rtc=1
       elif [ "${targetFPVersionNumber}" = "" ]
       then
          rtc=0
       elif [ "${FPCompare}" = "LT" ] 
       then
          echo "This will result in a FrontPage patch version downgrade."
          echo
          myprompt 'yYnN' "Are you sure that you want to do this (y/n)" "N"
          if [ $answer = n ] || [ $answer = N ]
          then
             rtc=1
          fi
       fi
    fi
 fi

 echo

 unset ApacheCompare
 unset FPCompare
 unset sourceVersionNumber
 unset targetVersionNumber
 unset sourceFPVersionNumber
 unset targetFPVersionNumber
 unset answer

 return $rtc

}

compareVersions()
{
 Version1=$1
 Version2=$2
 RetName=$3

 eval ${RetName}=`(echo $Version1 ; echo $Version2) | $awk -F . '
                                    {if (NR==1) {A=$1;B=$2;C=$3;D=$4; next}}
                                                {if ((A > $1) ||
                                                    ((A == $1) && ((B > $2) ||
                                                    ((B == $2) && ((C > $3) ||
                                                    ((C == $3) && (D > $4))))))) {print "GT";next}}
                                                {if ((A == $1) && (B == $2) && 
                                                     (C == $3) && (D == $4)) {print "EQ";next}}
                                                {print "LT"}'`

}

upgradeServer()
{
 echo "Upgrading FrontPage Webs..."
 cp -p $httpdfile ${httpdfile}.orig || 
     {
         echo
         echo "ERROR:  Unable to copy ${httpdfile} to ${httpdfile}.orig" 
         return 1
     }
 
 cp ${NEWHTTPD} ${httpdfile} || 
     {
         echo
         echo "ERROR:  Unable to copy ${fpexe} to ${httpdfile}"
         return 1
     }
     
 rm -f /usr/local/frontpage/version${VERSION}/apache-fp/suidkey

 ps=`$psea | tail -10` ; echo $ps | sed -e 's/ //g' | cut -c10-137 > /usr/local/frontpage/version${VERSION}/apache-fp/suidkey

 chown root /usr/local/frontpage/version${VERSION}/apache-fp/suidkey
 chmod 600 /usr/local/frontpage/version${VERSION}/apache-fp/suidkey
   
 return 0
}

checkPermissions()
{
 retval=0

 apachedir="/usr/local/frontpage/version${VERSION}/apache-fp"

 echo 
 echo "Chowning $apachedir to root..." 
 chown root $apachedir ||
   (
    echo "ERROR:  Unable to chown $apachedir to root" 
    retval=1
   )

 echo 
 echo "Chmoding $apachedir to 711..." 
 chmod 711 $apachedir ||
   (
    echo "ERROR:  Unable to chown $apachedir to 711" 
    retval=1
   )

 apachedir="/usr/local/frontpage/version${VERSION}/apache-fp/_vti_bin"

 echo 
 echo "Chowning $apachedir to root..." 
 chown root $apachedir ||
   (
    echo "ERROR:  Unable to chown $apachedir to root" 
    retval=1
   )

 echo 
 echo "Chmoding $apachedir to 755..." 
 chmod 755 $apachedir ||
   (
    echo "ERROR:  Unable to chown $apachedir to 755" 
    retval=1
   )

 fpexe="/usr/local/frontpage/version${VERSION}/apache-fp/_vti_bin/fpexe"
 echo 
 echo "Chowning $fpexe to root..." 
 chown root $fpexe ||
 {
    echo "ERROR:  Unable to chown $fpexe to root" 
    retval=1
 }

 echo "Setting $fpexe to SUID..." 
 chmod u+s $fpexe ||
 {
    echo "ERROR:  Unable to set SUID for $fpexe" 
    retval=1
 } 

 echo

 return $retval

}

UpgradeServers()
{
 cat <<EOF 

The file /usr/local/frontpage/version${VERSION}/change_server_results.txt
will contain Success/Fail status for the upgrades.  When the upgrade 
has completed, you should examine this file to make sure that all of the 
upgrades were successful.

EOF

 $echo "Hit enter to continue${nnl}" 
 read continue
 echo

 createdate=`date`
 cat >/usr/local/frontpage/version${VERSION}/change_server_results.txt <<EOF
#
# Server Upgrade Results
#
# Automatically generated by change_server.sh on $createdate
#
EOF

 for weconfigfile in /usr/local/frontpage/*.cnf
 do
    echo 
    echo "Upgrading using configuration file:  "$weconfigfile 
    if IsItApache $weconfigfile
    then
        if verifywebserver $weconfigfile
        then
            if UpgradeServer $weconfigfile
            then
                echo
            else
                echo "Upgrade Failed      $weconfigfile" >> /usr/local/frontpage/version${VERSION}/change_server_results.txt
                echo "ERROR:  Server upgrade failed!"
                echo "Continuing with next server." 
                $echo "Hit enter to continue${nnl}" 
                read continue
            fi
        else
            echo "Cancelling upgrade..."
            echo "Upgrade Failed      $weconfigfile" >> /usr/local/frontpage/version${VERSION}/change_server_results.txt
        fi
    fi
 done

}

verifywebserver()
{
 weconfigfile="$1"
 
 conf=`basename $weconfigfile`
 port=`echo  $conf | sed -e '
     s/:/:/
     tmulti
     s/.cnf$//
     s/.*[^0-9]//
     q
     :multi
     s/.cnf$//'`

 configfile=`grep -i "^serverconfig:" $weconfigfile | sed -e 's/serverconfig://g'`
 httpdconfigfile=$configfile
 if [ ! -f "$configfile" ]
 then
     echo "$configfile does not exist."
     return 1
 fi
  
 servertype=`grep -i "^servertype:" $weconfigfile | sed -e 's/servertype://g'`
 configfiledir=`dirname $configfile`"/"

 getdocroot $weconfigfile ||
 {
    echo "ERROR:  Unable to get DocumentRoot/UserDir" 
    return 1
 } 

 case $servertype in 
      *pache*)   getHttpDirective $configfile AccessConfig $port
                 if [ "$param" != "" ]
                 then
                    case $param in
                        /*) accessconffile=$param  # fully qualified pathname
                            ;;
                        *)  file=`basename $param`
                            accessconffile="${configfiledir}${file}"
                            ;;
                    esac
                 else
                    accessconffile="${configfiledir}access.conf"
                    if [ ! -f $accessconffile ]
                    then
                         accessconffile=""
                    fi
                 fi

                 if [ "$accessconffile" != "" -a "$accessconffile" != "/dev/null" -a ! -f "$accessconffile" ]
                 then
                    echo "$accessconffile does not exist."
                    return 1
                 fi

                 ;;
 esac

 servicesfile=${docroot}"/_vti_pvt/services.cnf"

 if [ ! -f "$servicesfile" ]
 then
     echo "There are no services to upgrade for this web."
     return 1
 fi

 return 0
}

IsItApache()
{
 weconfigfile="$1"

 echo 
 echo "Checking configuration file ${weconfigfile} for server type..."
 servertype=`grep -i "^servertype:apache" $weconfigfile`
     
 if [ "$servertype" = "" ]
 then
     echo "Not apache server   $weconfigfile" >> /usr/local/frontpage/version${VERSION}/change_server_results.txt
     echo
     echo "This is not an apache server!  No upgrade to be done."
     return 1  
 else
     servertype=`echo $servertype | sed -e 's/servertype://g'`
     if [ "$servertype" = "apache-fp" ]
     then
         echo "Already apache-fp   $weconfigfile" >> /usr/local/frontpage/version${VERSION}/change_server_results.txt
         echo
         echo "This is already an apache-fp server!  No upgrade to be done."
         return 1
     fi
 fi

 return 0

}

UpgradeServer()
{
 weconfigfile="$1"

 servertype=`echo $servertype | sed -e 's/servertype://g'`
 configfile=`grep -i "^serverconfig:" $weconfigfile | sed -e '
            s/serverconfig://g'`
 myprompt 'yYnN' "This is an ${servertype} server!  Would you like to upgrade it (y/n)" "Y"
 if [ $answer = y ] || [ $answer = Y ]
 then               
     echo 
     echo "Updating information in ${weconfigfile}"
     echo "Moving $weconfigfile to ${weconfigfile}.orig"
     mv $weconfigfile ${weconfigfile}.orig ||
     (
         echo "Unable to move $weconfigfile!"
         return 1
     )

     echo "Creating new $weconfigfile and setting servertype..."
     sed -e s/servertype:.*/servertype:apache-fp/g ${weconfigfile}.orig > $weconfigfile ||
     (
         echo "Unable to create new $weconfigfile!  If the file has"
         echo "been corrupted you should be able to replace it with"
         echo "the backup (${weconfigfile}.orig)"
         return 1 
     )
        
     case $configfile in
     *fakeconf*) SetConfigFile $weconfigfile $configfile || return 1 ;;
     *) echo "Config file setting does not appear to be a fakeconf.  Continuing..." ;;
     esac
            
     echo
     echo "Preparing to upgrade FrontPage Server..."
    
     DoUpgrade $weconfigfile  ||
     (
         return 1
     )
     echo "Upgrade Successful  $weconfigfile" >> /usr/local/frontpage/version${VERSION}/change_server_results.txt
 else
     echo "User cancelled   $weconfigfile" >> /usr/local/frontpage/version${VERSION}/change_server_results.txt
     echo
     echo "Server not upgraded!  Proceeding to the next server."
 fi

 return 0
}

chownexistingservers()
{
 retval=0

 echo "Preparing to chown webs..." 
 cat <<EOF

Your webs have been upgraded to use the new Apache-fp Server.  The next step
is to chown the web in order to guarantee that the extensions will work 
properly.  At this point you have two options:

   1. This script will prompt you interactively for an owner and group of
      each web and then perform the chown.  If you do not have a lot of 
      webs you might want to choose this option.

   2. This script will generate a script, which you can edit to fill in the
      owner and group for each web, to run at a later date.  If you have a
      large number of webs you might want to choose this option.

EOF

     echo "Would you like to be prompted interactively for"
     myprompt 'yYnN' "each webs owner/group (y/n)" "Y"
     if [ $answer = y ] || [ $answer = Y ]
     then
        chownwebs 
     else
        generatechownscript $file  ||
        (
            echo "ERROR:  Server chown failed!  Continuing with next server." 
            $echo "Hit enter to continue${nnl}" 
            read continue
        )
     fi
     return $retval
}

chownwebs()
{
 retval=0

 for weconfigfile in /usr/local/frontpage/*.cnf
 do
     if grep Successful /usr/local/frontpage/version${VERSION}/change_server_results.txt | grep ${weconfigfile} > /dev/null
     then
         chownWeb $weconfigfile
     else
         echo
         echo "Web ${weconfigfile} was not upgraded."
         echo "See /usr/local/frontpage/version${VERSION}/change_server_results.txt" 
         echo "Skipping chown..."
     fi

 done

 return $retval
}

chownWeb()
{
 weconfigfile=$1

 echo 
 conf=`basename $weconfigfile`
 webport=`echo  $conf | sed -e '
     s/:/:/
     tmulti
     s/.cnf$//
     s/.*[^0-9]//
     q
     :multi
     s/.cnf$//'`

 port=$webport

 echo "Processing webs in port $webport..."
 echo

 servertype=`grep -i "^servertype:" $weconfigfile | sed -e 's/servertype://g'`
 configfile=`grep -i "^serverconfig:" $weconfigfile | sed -e 's/serverconfig://g'`
 configfiledir=`dirname $configfile`"/"

 getdocroot $weconfigfile ||
 {
    echo "ERROR:  Unable to get DocumentRoot/UserDir" 
    return 1
 } 

 servicesfile=${docroot}"/_vti_pvt/services.cnf"
 
 exec 4<&0
 exec <$servicesfile
 n=0
 while read service
 do 
    if [ $service = "/" ]
    then
       webname=""
       webtext="root web"
       web=""
    else
       webname="$service"
       webtext="$service"
       web="-w $webname"
    fi
    exec 5<&0
    exec 0<&4

    getdocroot $weconfigfile ||
    {
        echo "ERROR:  Unable to get DocumentRoot/UserDir" 
        return 1
    } 

    case $service in
       /~*)  owner=`echo $service | sed -e 's/\///'`

             webowner=`echo $service | sed -e 's/\/~//'`
             homedir=`finger $webowner |  $awk ' { if (NR==2) print $2}'`

             if [ -d "${homedir}/${userdir}" ]
             then
                 echo "Web ${webtext} on port ${webport} will be owned by ${webowner}"
                 defwebgroup=`$lsg ${homedir}/${userdir} | $awk ' { print $4}'`
                 exists=0
             else
                 exists="${homedir}/${userdir}"
             fi
             ;;
       *)    if [ -d "${docroot}/${service}" ]
             then
                 defwebowner=`$lsg ${docroot}${service} | $awk ' { print $3}'`
                 defwebgroup=`$lsg ${docroot}${service} | $awk ' { print $4}'`
                 $echo "Who should own web ${webtext} on port ${webport} [${defwebowner}]:  ${nnl}"
                 read webowner
                 if [ "$webowner" = "" ]
                 then
                     webowner=$defwebowner
                 fi
                 exists=0
             else
                 exists="${docroot}/${service}"

             fi
             ;;
    esac

    if [ "$exists" = "0" ]
    then
        $echo "What should the group for web ${webtext} on port ${webport} be [${defwebgroup}]:  ${nnl}"
        read webgroup
        if [ "$webgroup" = "" ]
        then
            webgroup=$defwebgroup
        fi


        /usr/local/frontpage/version${VERSION}/bin/fpsrvadm.exe -o chown -p $webport $web -xUser $webowner -xGroup $webgroup ||
        {
            echo 
            echo "ERROR:  Unable to chown web ${webtext} in port ${webport}"
            $echo "Hit enter to continue${nnl}" 
            read continue
        }
    else
        echo "ERROR:  web $service - $exists does not exist!  Skipping to next web."  
    fi
        exec 0<&5
 done
 exec <&4

}

generatechownscript()
{
 retval=0
 scriptout="/usr/local/frontpage/version${VERSION}/fp_chown.sh"
 createdate=`date`

 cat <<EOF

A script will be generated in ${scriptout} 
which you can edit to chown your webs at a future date.  You will need 
to edit the script and set the owner and group for each web before 
running the script.

EOF

 cat >$scriptout <<EOF 
#! /bin/sh
#
#
# Copyright 1996 Microsoft Corporation -- All Rights Reserved.
#
# Automatically generated by change_server.sh on $createdate
#
# You will need to edit this script before running it.  Change each 
# <OWNER> and <GROUP> to reflect the ownership/group that you want 
# set for the web.
#
# Example:  80 /testweb webowner webgroup
#

VERSION="4.0"

chown_web()
{
 port=\$1
 webname=\$2
 webowner=\$3
 webgroup=\$4

 retval=0

 if [ "\$webowner" = "<OWNER>" ] || [ "\$webgroup" = "<GROUP>" ]
 then
     echo "Owner/Group not specified for web \$webname on \$port!  Skipping to next web..."
 else
     if [ "\$webname" != "/" ]
     then
        webname=\`echo \$webname | sed -e 's%^/%%g'\`
        webtext="\$webname"
        web="-w \$webname"
     else
        webtext="root web"
        web=""
     fi
     echo
     echo "Chowning web \${webtext} in port \${port} to owner \${webowner} group \${webgroup}"
     /usr/local/frontpage/version${VERSION}/bin/fpsrvadm.exe -o chown -p \$port  \$web  -xUser \$webowner -xGroup \$webgroup
 fi
}

while read port webname webowner webgroup
do
    chown_web \$port \$webname \$webowner \$webgroup
done <<ENDCHOWN
EOF

 for weconfigfile in /usr/local/frontpage/*.cnf
 do
     if grep Successful /usr/local/frontpage/version${VERSION}/change_server_results.txt | grep ${weconfigfile} > /dev/null
     then 
         addChownWeb $weconfigfile
     else
         echo
         echo "Web ${weconfigfile} was not upgraded."
         echo "See /usr/local/frontpage/version${VERSION}/change_server_results.txt" 
         echo "Skipping chown..."
     fi
 done

 echo "ENDCHOWN" >>$scriptout

 chmod 764 $scriptout

 return $retval
}

addChownWeb()
{
 echo 
 conf=`basename $weconfigfile`
 webport=`echo  $conf | sed -e '
     s/:/:/
     tmulti
     s/.cnf$//
     s/.*[^0-9]//
     q
     :multi
     s/.cnf$//'`

 port=$webport

 echo "Adding webs in port ${webport} to chown script..."
 servertype=`grep -i "^servertype:apache" $weconfigfile | sed -e 's/servertype://g'`
 configfile=`grep -i "^serverconfig:" $weconfigfile | sed -e 's/serverconfig://g'`
 configfiledir=`dirname $configfile`"/"
 case $servertype in 
     *pache-fp*) getdocroot $weconfigfile ||
                 {
                     echo "ERROR:  Unable to get DocumentRoot/UserDir" 
                     return $retval
                 } 
                 ;;
              *) echo "Not an apache-fp web! Skipping to next web..." 
                 return $retval
                 ;;
 esac

 servicesfile="${docroot}/_vti_pvt/services.cnf"
 if [ -r $servicesfile ]
 then
     exec 4<&0
     exec <$servicesfile
     n=0
     while read service
     do 
        if [ $service = "/" ]
        then
            webtext="root web"
        else
            webtext="$service"
        fi
        case $service in
           /~*)  owner=`echo $service | sed -e 's/\///'`
                 webowner=`echo $service | sed -e 's/\/~//'`
                 homedir=`finger $webowner |  $awk ' { if (NR==2) print $2}'`
                 if [ -d "${homedir}/${userdir}" ]
                 then
                     webgroup=`$lsg ${homedir}/${userdir} | $awk ' { print $4}'`
                     exists=0

                 else
                     exists="${homedir}/${userdir}"
                 fi
                 ;;
             *)  if [ -d "${docroot}/${service}" ]
                 then
                     webowner=`$lsg ${docroot}${service} | $awk ' { print $3}'`
                     webgroup=`$lsg ${docroot}${service} | $awk ' { print $4}'`
                     exists=0
                 else
                     exists="${docroot}/${service}"
                 fi
                 ;;
        esac

     if [ "$exists" = "0" ]
     then
        echo "web ${webtext}"
        echo "$webport $service $webowner $webgroup" >> $scriptout
     else
        echo "ERROR:  web ${webtext}- Path $exists does not exist!  Skipping to next web."  
     fi        
     done
     exec <&4
 else
     echo "Unable to read $servicesfile! Skipping to next port."
 fi

}

SetConfigFile()
{
 defconfigfile=`echo $2 | sed -e 's/fakeconf\///g'`
 
 configfile=""
 while ( [ "$configfile" = "" ] || [ ! -f $configfile ] )
 do
     $echo "Server config filename: [${defconfigfile}]  ${nnl}" 
     read configfile
     if [ "$configfile" = "" ]
     then
        configfile="$defconfigfile"
     fi
 done
                           
 echo "Setting serverconfig to $configfile..."
 mv $weconfigfile ${weconfigfile}.bck ||
 {
    echo "Unable to update $weconfigfile!"
    return 1
 }
 sed -e s%serverconfig:.*%serverconfig:$configfile%g ${1}.bck > $1  ||
 {
    echo "Unable to create new $weconfigfile!"
    echo "If the file has been corrupted you should be able to replace it with"
    echo "the backup file (${weconfigfile}.orig)"
    rm ${weconfigfile}.bck
    return 1 
 }

 rm ${weconfigfile}.bck                          
 return 0
}

DoUpgrade()
{
 retval=0
 weconfigfile="$1"

 bindir="/usr/local/frontpage/version${VERSION}/bin/"

 conf=`basename $weconfigfile`
 port=`echo  $conf | sed -e '
    s/:/:/
    tmulti
    s/.cnf$//
    s/.*[^0-9]//
    q
    :multi
    s/.cnf$//'`

 echo "Upgrading server "$port 
 
 cd /usr/local/frontpage/version"$VERSION"/bin
 fpsrvadm.exe -o upgrade -p $port -type apache-fp
 
 return $retval
}

getparam() {
#
# gets the value of parameters from the config file
#
 directive=$1
 gpconfigfile=$2
 port=$3
 msg=$4

 getDirective $httpdconfigfile $directive $port   # try httpd.conf first
 if [ "$param" = "" -a -f "$gpconfigfile" ]       # try again w/configfile
 then
    getDirective $gpconfigfile $directive $port 
 else
    gpconfigfile=$httpdconfigfile
 fi
 echo $msg $gpconfigfile
 if [ "$param" = "" ]
 then
    return 1;
 else
    return 0;
 fi
}

getdocroot()
{
 weconfigfile=$1
 virtweb=`echo  $weconfigfile | sed -e '
         s/:/:/
         tmulti
         s/.cnf$//
         s/.*[^0-9]//
         q
         :multi
         s/:[0-9]*.cnf$//'`
 virtweb=`basename $virtweb`

 port=`echo  $weconfigfile | sed -e '
     s/:/:/
     tmulti
     s/.cnf$//
     s/.*[^0-9]//
     q
     :multi
     s/.cnf$//'`

 servertype=`grep -i "^servertype:" $weconfigfile | sed -e 's/servertype://g'`
 configfile=`grep -i "^serverconfig:" $weconfigfile | sed -e '
             s/serverconfig://g
             s/fakeconf.*\///'`

 echo
 echo "Getting DocumentRoot and UserDir."

 if [ ! -f "$configfile" ]
 then
     echo "$configfile does not exist."
     return 1
 fi

 configfiledir=`dirname $configfile`"/"
  
 docroot=""

 case $weconfigfile in
      *:*) getHttpVirtualDirective $configfile $port DocumentRoot
           docroot=$param

           if [ "$docroot" = "" ]
           then
               echo "VirtualHost block does not contain DocumentRoot directive."
               getHttpDirective $configfile ResourceConfig $port
               if [ "$param" != "" ]
               then
                   case $param in
                       /*) resconffile=$param  # fully qualified pathname
                           ;;
                       *)  file=`basename $param`
                           resconffile="${configfiledir}${file}"
                           ;;
                   esac
               else
                   resconffile="${configfiledir}srm.conf"
                   if [ ! -f $resconffile ]
                   then
                       resconffile=""
                   fi
               fi
               getparam DocumentRoot $resconffile $port "Getting DocumentRoot from "
               docroot=$param
           fi
 
           getHttpVirtualDirective $configfile $port UserDir
           userdir=$param

           if [ "$userdir" = "" ]
           then
               echo "VirtualHost block does not contain UserDir directive."
               getHttpDirective $configfile ResourceConfig $port
               resconffile=$param
               if [ "$param" != "" ]
               then
                   case $param in
                       /*) resconffile=$param  # fully qualified pathname
                           ;;
                       *)  file=`basename $param`
                           resconffile="${configfiledir}${file}"
                           ;;
                   esac
               else
                   resconffile="${configfiledir}srm.conf"
                   if [ ! -f $resconffile ]
                   then
                       resconffile=""
                   fi
               fi
               getparam UserDir $resconffile $port "Getting UserDir from "
               userdir=$param
           fi
           ;;
        *) case $servertype in 
                *etscape*) echo "Getting DocumentRoot from ${configfiledir}obj.conf."
                           docroot=`grep -i 'document-root' ${configfiledir}obj.conf`
                           docroot=`echo $docroot | sed -e'
                           s/.*root="//
                           s/".*//'`
                           
                           echo "Getting userdir from ${configfiledir}obj.conf."
                           userdir=`grep -i 'from="/~"' ${configfiledir}obj.conf`
                           userdir=`echo $docroot | sed -e'
                           s/.*subdir="//
                           s/".*//'`
                           ;;

                        *) getHttpDirective $configfile ResourceConfig $port
                           if [ "$param" != "" ]
                           then
                               case $param in
                                   /*) resconffile=$param  # fully qualified pathname
                                   ;;
                                   *)  file=`basename $param`
                                       resconffile="${configfiledir}${file}"
                                   ;;
                               esac
                           else
                               resconffile="${configfiledir}srm.conf"
                               if [ ! -f $resconffile ]
                               then
                                   resconffile=""
                               fi
                           fi

                           if [ "$resconffile" != "" -a "$resconffile" != "/dev/null" -a ! -f "$resconffile" ]
                           then
                               echo "ERROR: $resconffile does not exist!"
                               return 1
                           fi

                           getparam DocumentRoot $resconffile $port "Getting DocumentRoot from "
                           docroot=$param
 
                           getparam UserDir $resconffile $port "Getting UserDir from "
                           userdir=$param
                           ;; 
           esac  
           ;;
 esac

 if [ ! -d "$docroot" ]
 then
     echo "ERROR:  ${docroot} does not exist!"
     return 1
 fi

 if [ "$docroot" = "" ]
 then
     echo "ERROR:  DocumentRoot not defined!"
     return 1
 fi

 if [ "$userdir" = "" ]
 then
     echo "WARNING:  UserDir not defined."
 fi

 echo
 echo "DocumentRoot: $docroot"

 if [ "$userdir" = "" ]
 then
     echo "WARNING:  UserDir not defined."
 else
     echo "UserDir: $userdir"
 fi

 echo

 return 0

}

getHttpDirective()
{
 configfile=$1
 directive=$2
 port=$3

 getDirective $configfile $directive $port
 if [ "$param" = "" ]
 then
     echo "Directive $directive not found."
 else 
     echo "Found Directive $directive, value $param."
 fi
}

getDirective()
{
 gdconfigfile=$1
 directive=$2
 port=$3

 if [ "$gdconfigfile" = "" ]
 then
    return 0
 fi

 case $port in
    *:*) getHttpVirtualDirective $gdconfigfile $port $directive ;;
      *) getHttpRootDirective $gdconfigfile $directive ;;
 esac
}

getMixedCase() {

#
# getMixedCase takes a string and converts it to a regular expression which
# matches all possible case combinations.
#
# String = [Ss][Tt][Rr][Ii][Nn][Gg]
#

mc_string=`echo $1 | $awk "
               BEGIN {
                   newstring = \"\";
                   oldstring = \"$1\"; 

                   } 

                   $functions
 
                   {
                   
                   strlen = length(oldstring);

                   for ( i = 1; i <= strlen; ++i ) {
                       char = substr(oldstring, i, 1)
                       newstring = newstring \"[\" toupper(char) tolower(char) \"]\";
                   };
                   print newstring}"`


}

getHttpRootDirective()
{
 configfile=$1
 directive=$2

 getMixedCase $directive

 param=`cat $configfile | $awk "
            /^[^#]* *< *[Vv][Ii][Rr][Tt][Uu][Aa][Ll][Hh][Oo][Ss][Tt]/,/^[^#]* *< *\/[Vv][Ii][Rr][Tt][Uu][Aa][Ll][Hh][Oo][Ss][Tt]/ { next }
            /^[^#]* *$mc_string[ $TAB]/  { print \\\$2 }"` 
 
 return 0

}

getHttpVirtualDirective()
{
 configfile=$1
 port=$2
 directive=$3

 virtweb=`echo  $port | sed -e 's/:[0-9]*.$//'`
 virtweb=`basename $virtweb`

 getMixedCase $directive

 param=`cat $configfile | $awk "
                          BEGIN { value = \"\" }
                              { x=0 }
                              /^[^#]* *< *[Vv][Ii][Rr][Tt][Uu][Aa][Ll][Hh][Oo][Ss][Tt] +$virtweb/,/^[^#]* *< *\/[Vv][Ii][Rr][Tt][Uu][Aa][Ll][Hh][Oo][Ss][Tt]/ { x=1 }
                              /^[^#]* *$mc_string[ $TAB]/  { if (x==1) value =\\\$2 }
                          END { print value }"`

 if [ "$param" = "" ]
 then
    getHttpRootDirective $configfile $directive
 fi 

}

error()
{
 #
 # Print an error message and exit the program
 #

 echo 
 echo "Exiting due to an error!  Please fix the error and try again." 
 echo 
 
 exit 1
}

#
# This is the main part of the shell script.
#

  initialize
  checkuser || error
  banner
  InstallFPexe || error                   # Install fpexe
  UpgradeServers || error                 # Now upgrade the servers
  chownexistingservers || error           # Now chown the webs
 
  myprompt 'yYnN' "Would you like to set the default permissions (y/n)" "Y"
  if [ $answer = y ] || [ $answer = Y ]
  then               
      #
      # Run the external permissions script. 
      #
      /usr/local/frontpage/version${VERSION}/set_default_perms.sh
  fi
  cat <<EOF

  Installation completed!  You will need to stop the old server daemon
  and start the new one before your webs will work properly.
  Exiting... 
EOF
  exit 0





