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

#
# This is the main part of the shell script.
#
main() {
    initialize
    step1                               # setup environment
#    step2                               # untar
    $FPDIR/set_default_perms.sh         # Run the external permissions script.
    step3                               # upgrade/install
    
    echo 
    echo "Installation completed!  Exiting..." 
    
    exit 0
}

# main install steps
step1()
{
    echo 
    echo "Step 1.  Setting Up Installation Environment" 
    echo 
    
    checkuser      || error        # Check to make sure we are root
    banner         || error        # Display header/copyright info
    usrlocalexists || error        # Check to make sure that /usr/local exists
    checkforaccess || error        # Check for RWX access to /usr/local
    wheretoinstall || error        # Find out where to install the extensions
}

step2()
{
    echo 
    echo "Step 2.  Untarring the Extensions and Checking Protections" 
    echo 
    
    untarext       || error        # Untar the extensions
}

step3()
{
    echo 
    echo "Step 3.  Upgrading/Installing the extensions" 
    echo 
    
    migrateoldconfig        || error   # Migrate old frontpage.cnf (if any)
#    change_server           || error   # upgrade httpd
    upgradeexistingservers  || error   # Check to see if servers need upgrading
    upgrade="yes"
    chownexistingservers    || error   # Now chown the webs
    handlelanguage          || error   # configure some global settings
    installrootweb          || error   # Install the root web
    installadminweb         || error   # Install the FrontPage Server Administration Web
    installnewsubwebs $PORT || error   # Install new servers
    installvirtualwebs      || error   # Install any virtual webs
}

################################################################################
# basic utility functions
#

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

getpassword()
{
    prompt=$1
    PASSWORD=""
    until [ "$PASSWORD" != "" ]
    do
        $echo "$prompt:  ${nnl}" 
        stty -echo
        read password1
        stty echo
        echo
        $echo "Re-enter $prompt:  ${nnl}" 
        stty -echo
        read password2
        stty echo
        echo 
        if [ "$password1" = "$password2" ]
        then
            PASSWORD=$password1
        fi
    done
    
    return 1
}

getHomedir()
{
    user=$1
    shell=`egrep "csh|ksh|bash" /etc/shells | head -1`
    homedir=`$shell -f -c 'echo ~'$user`
}

# Print an error message and exit the program.
error()
{
    echo 
    echo "Exiting due to an error!  Please fix the error and try again." 
    echo 
    
    exit 1
}

# Print a useful error message and exit the program.
die() {
    echo "Aborting, could not successfully $*"
    exit 1
}

initialize()
{
    VERSION="5.0"
    PATH=".:/bin:/usr/bin:/sbin:/usr/sbin:/usr/ucb:/etc:/usr/bsd"
    AP_TARGET=`/usr/local/sbin/apxs -q TARGET`
    AP_CONFDIR=`/usr/local/sbin/apxs -q SYSCONFDIR`
    INSTALLDIRDEFAULT="/usr/local/frontpage"
    NEWHTTPDNEW="/usr/local/frontpage/version${VERSION}/apache-fp/httpd"
    DEFAULTHTTPD="/usr/local/sbin/httpd"
    FPDIR="/usr/local/frontpage/version${VERSION}"

    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*)             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" ;;
        FreeBSD*)           machine="freebsd" ;;
        *)              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 
    
    case "$machine" in
         alpha) strings="strings -a"
                ;;
          bsdi) awk=awk
                ;;
       freebsd) awk=awk
                strings="strings -a"
                ;;
         hp700) awk=awk
                ;;
         linux) awk=awk
                psea="ps ea"
                strings="strings -a"
                ;;
        rs6000) strings="strings -a"
                ;;
           sgi) awk=nawk 
                lsg="ls -ld"
                ;;
       solaris) awk=nawk
                lsg="ls -ld"
                strings="strings -a"
                ;;
    solarisx86) awk=nawk
                lsg="ls -ld"
                ;;
             *)
                ;;
    esac
}

# Compare two version numbers, including all sub-versions (such as 5.0.2.1234)
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"}'`
}

################################################################################
# Step 1: Setup/Verify Environment
#

banner()
{
cat <<EOF

 fp_install.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
}

#
# The following functions do some initial checks that we are who we need to be
# and have the directories and permissions on the directories that we need
#
checkuser()
{
    # Make sure we are running as root.
    
    whoami=`whoami 2>/dev/null` || whoami=`/usr/bin/id | sed -e ' s/).*//; s/^.*(//;'`
    retval=0
    
    echo "Setting umask 002" 
    umask 002
    
    if [ $whoami != "root" ]
    then
        echo "ERROR:  Logged in as $whoami.  Must be root to do this installation!"
        retval=1
    else
        echo "Logged in as root." 
    fi
    
    return $retval
}

usrlocalexists()
{
    # Now lets make sure that /usr/local exists.
    
    localdir="/usr/local"
    prot=755
    retval=0
    
    if [ ! -d "$localdir" ]
    then
        myprompt 'yYnN' "$localdir does not exist.  Would you like to create it (y/n)" "Y"
        if [ $answer = y ] || [ $answer = Y ]
        then
            echo "Creating $localdir" 
            if mkdir "$localdir"
            then
                echo "Directory $localdir has been created." 
                if chmod "$prot" "$localdir"
                then
                    echo "Directory $localdir chmoded to $prot." 
                else
                    echo "ERROR:  Unable to chmod $localdir to $prot." 
                    retval=1
                fi
            else
                echo "ERROR:  Unable to create $localdir!" 
                retval=1
            fi
        else
            echo "ERROR:  Directory $localdir must exist!" 
            retval=1
        fi
    else
        if [ ! -d "$localdir" ]
        then
            echo "ERROR:  $localdir exists but is not a directory!" 
            retval=1
        else
            echo "Directory $localdir exists." 
        fi
    fi
    
    return $retval
}

checkforaccess()
{
    # Make sure that we have the correct access to /usr/local
    
    retval=0
    
    # Check to make sure that we have read access to the directory
    comma=""
    if [ ! -r /usr/local ]
    then
        noaccess="Read"
        comma=", "
    fi
    
    # Check to make sure that we have write access to the directory
    if [ ! -w /usr/local ]
    then
        noaccess="$noaccess${comma}Write"
        comma=", "
    fi
    
    # Check to make sure that we have execute access to the directory
    if [ ! -x /usr/local ]
    then
        noaccess="$noaccess${comma}Execute"
    fi
    
    if  [ "$noaccess" != "" ]
    then
        echo "ERROR:  Root does not have $noaccess access to /usr/local!" 
        retval=1
    else
        echo "Root has necessary access to /usr/local." 
    fi
    
    return $retval
}

#
# Find out where to install the extensions and create directory and/or link
# as necessary.
#
wheretoinstall()
{
    retval=0
    
        installdir=$INSTALLDIRDEFAULT
    installdir=`dirname $installdir`/`basename $installdir`

            if chmod "$prot" "$installdir"
            then
                echo "Directory $installdir chmoded to $prot." 
            else
                echo "ERROR:  Unable to chmod $installdir to $prot." 
                retval=1
            fi
    
    if [ "$installdir" != "/usr/local/frontpage" ]
    then
        if [ ! -d "/usr/local/frontpage" ]
        then
            if ln -s "$installdir" "/usr/local/frontpage"
            then
                echo "Snapped link /usr/local/frontpage --> $installdir"
            else
                echo "ERROR:  Unable to  snap link /usr/local/frontpage --> $installdir!" 
                retval=1
            fi
        else
            echo "ERROR:  Unable to snap link /usr/local/frontpage --> $installdir, /usr/local/frontpage already exists!" 
            retval=1
        fi
    fi
    
    return $retval 
}

###############################################################################
#
# Step 2: Untar the extensions into the installation directory and check
#         permissions
#
untarext()
{
    retval=0
    
    if [ -d "${installdir}/version${VERSION}" ]
    then
        echo "Version $VERSION FrontPage Server Extensions found."
        myprompt 'yYnN' "Would you like to overwrite? (y/n)" "Y"
        echo 
        if [ $answer = n ] || [ $answer = N ]
        then
            echo "No need to un-tar the extensions.  Continuing..."
            return $retval
        else
            echo "Looking for tar file..."
        fi
    else
        echo "Version $VERSION FrontPage Server Extensions not found."
        echo "Looking for tar file..."
    fi
    
    vtfile="fp50.$machine.tar"
    echo "Platform is $machine." 
    
    vtfilelocation="`pwd`/"
    
    getextfilename $vtfilelocation $vtfile || return 1
    
    olddir=`pwd`

    if [ "$installdir" != "/usr/local/frontpage" ]
    then
        cd $installdir
    else
        cd /usr/local
    fi
    case $fullvtfile in 
     *tar) echo "Untarring file $fullvtfile into /usr/local..." 
           tar -xf $fullvtfile ;;
       *Z) echo "Uncompressing/Untarring file $fullvtfile into /usr/local..."
           zcat $fullvtfile | tar -xf - 
           ;;
      *gz) zcat=""
           while [ "$zcat" = "" ] || [ ! -f "$zcat" ]
           do
               $echo "Where is the zcat which can uncompress gz files? ${nnl}"
               read zcat
               base=`basename zcat`
               case $base in
                  zcat) ;; 
                     *) zcat=`dirname $zcat`/`basename $zcat`/zcat ;;
               esac
           done
           echo "Uncompressing/Untarring file $fullvtfile into /usr/local..."
           $zcat $fullvtfile | tar -xf -
           ;;
        *) echo "ERROR:  Unknown file type: $fullvtfile"
           return 1
           ;;
    esac
    
    if [ "$installdir" != "/usr/local/frontpage" ]
    then
        mv frontpage/* .
        rm -rf frontpage
    fi
    
    cd $olddir
    
    return $retval
}

# get the name of the tarball file
# used by untarext
getextfilename()
{
    vtfilelocation=$1
    vtfile=$2
    fullvtfile="${vtfilelocation}${vtfile}"
    if [ ! -f "$fullvtfile" ]
    then
        if [ -f "${fullvtfile}.Z" ]
        then
            fullvtfile="${fullvtfile}.Z"       
        else
            if [ -f "${fullvtfile}.gz" ]
            then
                fullvtfile="${fullvtfile}.gz"
            else
                if [ -f "${fullvtfile}.z" ]
                then
                    echo "Renaming ${vtfile}.z to ${vtfile}.Z"
                    mv "${fullvtfile}.z" "${fullvtfile}.Z"
                    fullvtfile="${fullvtfile}.Z"
                else
                    echo "Cannot find the FrontPage Server Extensions tar file in ${vtfilelocation}." 
                    $echo "Which directory is the file located in (X to cancel)?  ${nnl}" 
                    read vtfilelocation
                    if [ "$vtfilelocation" = "X" ] || [ "$vtfilelocation" = "x" ]
                    then
                        return 1
                    else
                        vtfilelocation=`echo $vtfilelocation |sed -e 's/\/$//'`
                        
                        if [ ! -d "$vtfilelocation" ]
                        then
                            vtfilelocation=`dirname $vtfilelocation`
                        fi
                        getextfilename $vtfilelocation/ $vtfile
                    fi
                fi
            fi
        fi
    fi
}

###############################################################################
#
# Step 3: Upgrade/Install extensions
#

#
# Look for older versions of frontpage.cnf, and migrate them into the current
#
migrateoldconfig()
{
    retval=0
    
    echo "Checking for previous versions of FrontPage Server Extensions to upgrade..." 
    
    upgrade=""
    for file in ${installdir}/version*/frontpage.cnf
    do
        if [ $file != ${installdir}/version${VERSION}/frontpage.cnf ]
        then
            upgrade="$upgrade $file"
        fi
    done
    
    if [ "$upgrade" != "" ]
    then
        upgrade=`echo $upgrade | sed -e 's/.*version//g' -e 's/\/frontpage\.cnf//g'`
        echo "You have an older version of FrontPage Server Extensions installed ($upgrade).";
        myprompt 'yYnN' "Would you like to migrate these settings to version $VERSION now (y/n)" "Y"
        
        if [ $answer = n ] || [ $answer = N ] ; then
            upgrade=""
            return $retval;
        fi
    else
        echo "You have no previous versions of FrontPage Server Extensions installed."
        echo "There are no settings to migrate!"
        return $retval;
    fi
    echo
    
    for ver in $upgrade ; do
        mergefiles ${installdir}/version${ver}/frontpage.cnf $FPDIR/frontpage.cnf $FPDIR/frontpage.cnf
    done

    # mergefiles mucks w/ owner/group/mode, so we must reset them here
    chown bin $FPDIR/frontpage.cnf || die chown frontpage.cnf
    chgrp bin $FPDIR/frontpage.cnf || die chgrp frontpage.cnf
    chmod 664 $FPDIR/frontpage.cnf || die chmod frontpage.cnf
    
    return $retval
}

# keys in "in1" replace keys in "in2".  keys in only one file are maintained
mergefiles()
{
    in1=$1
    in2=$2
    out=$3
    outreal=$out
    if [ $out = $in1 -o $out = $in2 ]
    then
        out=${outreal}.new
    fi
    
    cat $in1 > $out
    for key in `sed -e 's/:.*//g' $in2` ; do
        if [ `grep -i -c "^$key:" $in1` = 0 ]
        then
            grep -i "^$key:" $in2 >> $out
        fi
    done
    
    if [ $out != $outreal ]
    then
        mv -f $out $outreal
    fi
}

# Check to see if servers need upgrading
upgradeexistingservers()
{
    retval=0
    
    echo "Checking for existing web servers to upgrade..." 
    
    upgrade="none"
    for file in ${installdir}/*.cnf
    do
        if [ "$file" = "${installdir}/*.cnf" ]
        then
            echo "No existing web servers found to upgrade." 
            return $retval
        fi
        
        cat <<EOF
 
Existing web servers were found; do you want to upgrade them now?
(If you answer "no", you can safely run this script again and answer "yes"
to upgrade your servers later.)

EOF
        myprompt 'yYnN' "Upgrade now (y/n)" "Y"
        
        if [ $answer = n ] || [ $answer = N ]
        then
            upgrade="no"
            echo "For details on how to upgrade servers manually, please see" 
            echo "the Server Extension Resource Kit (SERK), located at"
            echo "http://www.microsoft.com/frontpage"
            echo
            return $retval
        else
            upgrade="yes"
        fi
        break
    done

    cat <<EOF
 
The file ${installdir}/version${VERSION}/upgrade_results.txt will
contain Success/Fail status for the upgrades.  When the upgrade is
complete you should examine this file to make sure that all of the
upgrades completed successfully.

EOF
    $echo "Hit enter to continue${nnl}" 
    read continue
    echo
    
    echo "All existing servers will now be upgraded:" 
    echo " " 
    
    createdate=`date`
    cat >${installdir}/version${VERSION}/upgrade_results.txt <<EOF 
#
# Server Upgrade Results
#
# Automatically generated by fp_install.sh on $createdate
#
EOF
    
    for weconfigfile in ${installdir}/*.cnf
    do
        echo 
        echo "Upgrading using configuration file:  "$weconfigfile 
        if verifywebserver $weconfigfile
        then
            if upgradeserver $weconfigfile
            then
                echo "Upgrade Successful  $weconfigfile" >> ${FPDIR}/upgrade_results.txt
            else
                echo "Upgrade Failed      $weconfigfile" >> ${FPDIR}/upgrade_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" >> ${FPDIR}/upgrade_results.txt
        fi
    done
    
    weconfigfile=""
    
    return $retval
}

# examine weX.cnf file, make sure it is a patched apache server
verifywebserver()
{
    weconfigfile="$1"
    
    conf=`basename $weconfigfile`
    webport=`echo  $conf | sed -e '
        s/:/:/
        tmulti
        s/.cnf$//
        s/.*[^0-9]//
        q
        :multi
        s/.cnf$//'`
    
    port=$webport
    
    echo "Verifying web server configuration..."
    
    configfile=`grep -i "^serverconfig:" $weconfigfile | sed -e '
                    s/serverconfig://g
                    s/fakeconf.*\///'`
    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`"/"

    if [ $servertype != "apache-fp" ]
    then
        echo "This version of FrontPage Server Extensions does not suppport"
        echo "$servertype servers.  We only support patched apache servers."
        echo "For more information about supported servers, please see" 
        echo "the Server Extension Resource Kit (SERK), located at"
        echo "http://www.microsoft.com/frontpage"
        return 1
    fi

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

    getHttpDirective $configfile AccessConfig $port
    if [ "$param" != "" ]
    then
        case $param in
            /dev/null) accessconffile=$configfile
                ;;
            /*) accessconffile=$param  # fully qualified pathname
                ;;
            *)  file=`basename $param`
                accessconffile="${configfiledir}${file}"
                ;;
        esac
	if [ ! -f $accessconffile ]
	then
	    echo "ERROR:  $accessconffile does not exist! Using $configfile instead."
	    accessconffile=$configfile
	fi
    else
        accessconffile="${configfiledir}access.conf"
        if [ ! -f $accessconffile ]
        then
	    echo "ERROR: No AccessConfig directive found, add 'AccessConfig /dev/null' to $configfile"
            accessconffile=$configfile
        fi
    fi
    if [ "$accessconffile" != "" -a "$accessconffile" != "/dev/null" -a ! -f "$accessconffile" ]
    then
        echo "ERROR: $accessconffile does not exist!"
        return 1
    fi

    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
}

# Go through all webs on all servers and chown the content appropriately
chownexistingservers()
{
    retval=0
    
    if [ "$upgrade" = "yes" ]
    then
        echo
        echo "Preparing to chown webs..." 
        cat <<EOF

All requested upgrades to the new FrontPage Server Extensions have taken place.
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
        myprompt 'yYnNsS' "Would you like interactive prompting for each webs owner/group (y/n)" "Y"
        if [ $answer = s ] || [ $answer = S ]
        then
            return $retval
        fi
        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
    fi
}

# Go through all webs on a given server and chown the content appropriately
chownwebs()
{
    retval=0
    
    for weconfigfile in ${installdir}/*.cnf
    do
        if grep Failed ${installdir}/version${VERSION}/upgrade_results.txt | grep ${weconfigfile} > /dev/null
        then
            echo
            echo "Upgrade of ${weconfigfile} failed."
            echo "See ${installdir}/version${VERSION}/upgrade_results.txt" 
            echo "Skipping chown..."
        else
            servertype=`grep -i "^servertype:" $weconfigfile|sed -e 's/servertype://g'`
            if [ "$servertype" != "apache-fp" ]
            then
                echo "Skipping non patched-apache web $weconfigfile"
            else
                chownWeb $weconfigfile
            fi
        fi
    done
    weconfigfile=""
    return $retval
}

# chown the content of a given web/subweb
chownWeb()
{
    weconfigfile=$1
    
    conf=`basename $weconfigfile`
    webport=`echo  $conf | sed -e '
        s/:/:/
        tmulti
        s/.cnf$//
        s/.*[^0-9]//
        q
        :multi
        s/.cnf$//'`
    
    port=$webport
    
    echo 
    echo "Processing webs in port $webport..."
    echo 
    
    configfile=`grep -i "^serverconfig:" $weconfigfile | sed -e '
                    s/serverconfig://g
                    s/fakeconf.*\///'`
    configfiledir=`dirname $configfile`"/"
    
    getdocroot $weconfigfile ||
    {
        echo "ERROR:  Unable to get DocumentRoot/UserDir"
        return 1
    }
    
    servicesfile=${docroot}"/_vti_pvt/services.cnf"
    
    # map our $servicesfile to STDIN so we can use "read" on it...
    exec 4<&0
    exec <$servicesfile
    n=0
    while read service
    do
        echo
        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
        }

        # Figure out who owns (or should own) this web.  Prompt if we can't
        # figure it out ourselves.
        case $service in
           /~*) owner=`echo $service | sed -e 's/\///'`
                webowner=`echo $service | sed -e 's/\/~//'`
                getHomedir $webowner
                
                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}'`
                    webowner=""
                    until [ "$webowner" != "" ]
                    do
                        $echo "Who should own web ${webtext} on port ${webport} [${defwebowner}]:  ${nnl}"
                        read webowner
                        if [ "$webowner" = "" ]
                        then
                            webowner=$defwebowner
                        fi
                    done
                    exists=0
                else
                    exists="${docroot}/${service}"
                fi
             ;;
        esac

        # We have the owner, now let's find the group
        if [ "$exists" = "0" ]
        then
            webgroup=""
            until [ "$webgroup" != "" ]
            do
                $echo "What should the group for web ${webtext} on port ${webport} be [${defwebgroup}]:  ${nnl}"
                read webgroup
                if [ "$webgroup" = "" ]
                then
                    webgroup=$defwebgroup
                fi
            done
            
            case $webport in 
               *:*) multihost="-m "`echo $webport | cut -d: -f1`
                    multiport="-p "`echo $webport | cut -d: -f2`
                    ;;
                 *) multihost=""
                    multiport="-p $webport"
                    ;;
            esac
            
            $FPDIR/bin/owsadm.exe -o chown $multiport $multihost $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
}

#
# Generate a script fp_chown.sh that will call "owsadm -o chown" for each web,
# Used when the user says they do not want to be prompted interactively for
# each web
# 
generatechownscript()
{
    retval=0
    scriptout="${FPDIR}/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-2001 Microsoft Corporation -- All Rights Reserved.
#
#          Automatically generated by fp_install.sh
#
# Automatically generated by fp_install.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="5.0"

chown_web()
{
    port=\$1
    webname=\$2
    webowner=\$3
    webgroup=\$4
    
    if [ "\$webowner" = "<OWNER>" ] || [ "\$webgroup" = "<GROUP>" ]
    then
        echo "WARNING:  Owner/Group not specified for web \$webname on \$port."
        echo "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
        case \${port} in
           *:*) multihost="-m "\`echo \${port} | cut -d: -f1\`
                multiport="-p "\`echo \${port} | cut -d: -f2\`
                ;;
             *) multihost=""
                multiport="-p \${port}"
                ;;
        esac
        echo
        echo "Chowning web \${webtext} in port \${port} to owner \${webowner} group \${webgroup}"
        /usr/local/frontpage/version${VERSION}/bin/owsadm.exe -o chown \$multiport \$multihost \$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 ${installdir}/*.cnf
    do
        if grep Failed ${installdir}/version${VERSION}/upgrade_results.txt | grep ${weconfigfile} > /dev/null
        then 
            echo
            echo "Upgrade of ${weconfigfile} failed."
            echo "See ${installdir}/version${VERSION}/upgrade_results.txt" 
            echo "Skipping chown..."
        else
            addChownWeb $weconfigfile
        fi
    done
    
    echo "ENDCHOWN" >>$scriptout
    
    chmod 764 $scriptout
    
    weconfigfile=""
    return $retval
}

# Very similar to chownWeb(), but stick results into a file for fp_chown.sh
addChownWeb()
{
    weconfigfile=$1
    
    echo 
    echo "Processing  $weconfigfile"
    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:" $weconfigfile|sed -e 's/servertype://g'`
    configfile=`grep -i "^serverconfig:" $weconfigfile | sed -e '
                s/serverconfig://g
                s/fakeconf.*\///'`
    configfiledir=`dirname $configfile`"/"
    getdocroot $weconfigfile ||
    {
        echo "ERROR:  Unable to get DocumentRoot/UserDir"
        return 1
    }
    
    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/\/~//'`
                    getHomedir $webowner
                    
                    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 "WARNING:  Unable to read $servicesfile!" 
        echo "Skipping to next port."
    fi
}

# upgrade a server
upgradeserver()
{
    retval=0
    weconfigfile="$1"
    bindir=$installdir'/version'$VERSION'/bin'
    conf=`basename $weconfigfile`
    webport=`echo  $conf | sed -e '
        s/:/:/
        tmulti
        s/.cnf$//
        s/.*[^0-9]//
        q
        :multi
        s/.cnf$//'`
    
    echo "Upgrading server "$webport

    case $webport in
       *:*) multihost="-m "`echo $webport | cut -d: -f1`
            multiport="-p "`echo $webport | cut -d: -f2`
            ;;
         *) multihost=""
            multiport="-p $webport"
            ;;
    esac
    
    # docroot is set by getdocroot which is called from verifywebserver which
    # is called before upgradeserver
    webowner=`$lsg ${docroot} | $awk ' { print $3}'`
    xuser="-xu $webowner"
    
    $bindir/owsadm.exe -o upgrade $multiport $multihost $xuser
    
    return $retval
}

# Install the root web
installrootweb()
{
    retval=0
    
    configfile=""
    admin=""
    port=""
    multihost=""
    webname=""
    webowner=""
    
    echo "  Note: Local version of Apache must use the FrontPage Apache patch."
    echo "  See http://www.microsoft.com/frontpage/ for more details."
    
    servertype="apache-fp"
    
    echo 
    echo "Note: If you have not installed the root web then you need to do it now." 
    echo
    myprompt 'yYnN' "Do you want to install a root web (y/n)" "Y"
    if [ $answer = n ] || [ $answer = N ]
    then
        return $retval
    fi
    
    echo " " 
    echo "Installing the root web..." 
    echo " " 
    
    webname="/"
    defconfigfile="${AP_CONFDIR}/${AP_TARGET}.conf"
    
    configfile=""
    while ( [ "$configfile" = "" ] || [ ! -f $configfile ] )
    do
        $echo "Server config filename:  [$defconfigfile] ${nnl}" 
        read configfile
        if [ "$configfile" = "" ]
        then
            configfile=$defconfigfile
        fi
    done
    httpdconfigfile=$configfile
    
    defadmin="fpadmin"
    admin=""
    until [ "$admin" != "" ]
    do
        $echo "FrontPage Administrator's user name:  [$defadmin] ${nnl}" 
        read admin
	if [ "$admin" = "" ]
	then
	    admin=$defadmin
	fi
    done
    
    getHttpRootDirective $configfile Port
    port=$param
    
    until [ "$port" != "" ]
    do
        $echo "Enter the new server's port number:  ${nnl}" 
        read port
    done
    weconfigfile="${installdir}/we${port}.cnf"
    
    getHttpRootDirective $configfile DocumentRoot
    docroot=$param
    if [ ! -d "$docroot" ]
    then
        echo "ERROR: $docroot does not exist!"
        return 1
    fi

    echo 
    getparam User $configfile $port "Getting User from "
    defwebowner=$param

    if [ "$defwebowner" = "" ]
    then
	defwebowner=`$lsg ${docroot}${service} | $awk ' { print $3}'`
    fi

    webowner=""
    until [ "$webowner" != "" ]
    do
        $echo "Unix user name of the owner of this new web: [$defwebowner]  ${nnl}"
        read webowner
        if [ "$webowner" = "" ]
        then
            webowner=$defwebowner
        fi
    done
    
    echo 
    getparam Group $configfile $port "Getting Group from "
    defgroup=$param

    if [ "$defgroup" = "" ]
    then
	defgroup=`$lsg ${docroot}${service} | $awk ' { print $4}'`
    fi

    webgroup=""
    until [ "$webgroup" != "" ]
    do
        $echo "Unix group of this new web: [$defgroup]  ${nnl}" 
        read webgroup
        if [ "$webgroup" = "" ]
        then
            webgroup=$defgroup
        fi
    done
    
    multihost="."
    if [ "$configfile" = "" ]
    then
        configfile="."
    fi
    
    PORT=$port
    
    echo "Installing root web into port $port..." 
    echo 
    installserver $port $multihost $webname $webowner $webgroup \
                  $admin $configfile $servertype ||
    {
        echo "ERROR:  $webname installation failed." 
        $echo "Hit enter to continue${nnl}" 
        read continue
        return $retval
    }
    
    return $retval
}

# set the global values for language and charactor encoding
handlelanguage()
{
    retval=0
    
    until [ "$charencoding" != "" ]
    do
        echo 
        echo "    1.  LATIN1 (ISO 8859-1)" 
        echo "    2.  LATIN2 (ISO 8859-2)" 
        echo "    3.  EUCJP  (Japanese EUC)" 
        echo "    4.  EUCKR  (Korean EUC)" 
        $echo "Which local character encoding does your system support: [1]  ${nnl}" 
        read charencodingnum
        echo
        
        case $charencodingnum in
           "") charencoding="latin1" ;;
          "1") charencoding="latin1" ;;
          "2") charencoding="latin2" ;;
          "3") charencoding="eucjp" ;;
          "4") charencoding="euckr" ;;
            *) echo "Invalid option!  Please try again."  ;;
        esac
    done
    
    until [ "$lang" != "" ]
    do
        echo 
        echo "    1.  English" 
        echo "    2.  French" 
        echo "    3.  German" 
        echo "    4.  Italian" 
        echo "    5.  Japanese" 
        echo "    6.  Spanish" 
        $echo "What should the default language be: [1] ${nnl}" 
        read langnum
        echo
        
        case $langnum in
            "") lang="en" ;;
           "1") lang="en" ;;
           "2") lang="fr" ;;
           "3") lang="de" ;;
           "4") lang="it" ;;
           "5") lang="ja" ;;
           "6") lang="es" ;;
             *) echo "Invalid option!  Please try again."  ;;
        esac
    done
    
    conffile=$FPDIR/frontpage.cnf
    echo "Setting "$conffile" to:" 
    echo 
    echo "defaultLanguage:${lang}"
    echo "localCharEncoding:${charencoding}"
    echo 
    echo "Copying ${conffile} to ${conffile}.orig"
    echo
    cp -p $conffile ${conffile}.orig ||
    {
        echo "ERROR:  Unable to backup $conffile to ${conffile}.orig!"
        $echo "Hit enter to continue${nnl}" 
        read continue
        return 1
    }
    
    echo "Creating and modifying new ${conffile}..."
    echo
    sed -e "s/defaultLanguage:.*/defaultLanguage:${lang}/g
            s/localCharEncoding:.*/localCharEncoding:${charencoding}/g" \
        ${conffile}.orig > $conffile ||
    {
        echo "ERROR:  Unable to create new $conffile!"
        echo "If the file has been corrupted you should be able to replace it with"
        echo "the backup file (${conffile}.orig)"
        $echo "Hit enter to continue${nnl}"
        read continue
        return 1
    }
    
    return $retval
}

# Install the FrontPage Server Administration Web
installadminweb()
{
    retval=0
    
    configfile=""
    admin=""
    port=""

    echo
    echo "Note: If you have not installed FrontPage Server Administration then you should do it now."
    echo
    myprompt 'yYnN' "Do you want to install FrontPage Server Administration (y/n)" "Y"
    if [ $answer = n ] || [ $answer = N ]
    then
	echo "You have chosen not to install FrontPage Server Administration.  If you wish"
	echo "to install it later, you will need to use the following command:"
	echo
	echo "${FPDIR}/owsadm.exe -o setadminport -p 10865 \\"
	echo "	-s ${AP_CONFDIR}/${AP_TARGET}.conf -u <FP Admin user>"
	echo
	echo "The FrontPage Server Administration setup will require the following change"
	echo "in ${AP_CONFDIR}/${AP_TARGET}.conf for <VirtualHost _default_:10865>:"
	echo
	echo "	AllowOverride AuthConfig Limit Indexes Options"
	echo
	echo "otherwise, the FrontPage Server Administration web will not allow you to login."
	echo
	echo "This will then make FrontPage Server Administration available at:"
	echo
	echo "	http://`hostname`:10865/fpadmcgi.exe"
	echo
        return $retval
    fi

    echo " "
    echo "Installing FrontPage Server Administration..."
    echo " "

    defconfigfile="${AP_CONFDIR}/${AP_TARGET}.conf"

    while ( [ "$configfile" = "" ] || [ ! -f $configfile ] )
    do
        $echo "Server config filename:  [$defconfigfile] ${nnl}"
        read configfile
        if [ "$configfile" = "" ]
        then
            configfile=$defconfigfile
        fi
    done
    httpdconfigfile=$configfile

    defadmin="fpadmin"
    until [ "$admin" != "" ]
    do
        $echo "FrontPage Server Administration user name:  [$defadmin] ${nnl}"
        read admin
        if [ "$admin" = "" ]
        then
            admin=$defadmin
        fi
    done

#   Need to determine if the FrontPage Server Administration Web was previously
#   installed and to which port it was installed on.

#    getHttpRootDirective $configfile Port
#    port=$param

    defport="10865"
    until [ "$port" != "" ]
    do
        $echo "Enter the FrontPage Server Administration port number:  [$defport] ${nnl}"
        read port
	if [ "$port" = "" ]
	then
	    port=$defport
	fi
    done

#    getHttpRootDirective $configfile DocumentRoot
#    docroot=$param
#    if [ ! -d "$docroot" ]
#    then
#        echo "ERROR: $docroot does not exist!"
#        return 1
#    fi

    echo "Installing FrontPage Server Administration on port $port..."
    echo
    ${FPDIR}/bin/owsadm.exe -o setadminport -p $port -s $configfile -u $admin || 
    {
        echo "ERROR:  FrontPage Server Administration installation failed."
        $echo "Hit enter to continue${nnl}"
        read continue
        return 1
    }
    echo
    echo "FrontPage Server Administration is now available at:"
    echo
    echo "	http://`hostname`:${port}/fpadmcgi.exe"
    echo
    echo "The FrontPage Server Administration setup requires the following change"
    echo "in ${AP_CONFDIR}/${AP_TARGET}.conf for <VirtualHost _default_:${port}>:"
    echo
    echo "	AllowOverride AuthConfig Limit Indexes Options"
    echo
    echo "otherwise, the FrontPage Server Administration web will not allow you to login."
    echo

    return $retval
}

# Install a web on a multihosted server
installvirtualwebs()
{
    retval=0
    
    echo
    echo "Installing Virtual Webs.." 
    echo 
    myprompt 'yYnN' "Do you want to install Virtual Webs (y/n)" "Y"
    if [ $answer = n ] || [ $answer = N ]
    then
        return $retval
    fi
    
    defaultconfigfile="${AP_CONFDIR}/${AP_TARGET}.conf"
    configfile=""
    while ( [ "$configfile" = "" ] || [ ! -f $configfile ] )
    do
        $echo "Server config filename [${defaultconfigfile}]:  ${nnl}" 
        read configfile
        if [ "$configfile" = "" ]
        then
            configfile=$defaultconfigfile
        fi
    done
    httpdconfigfile=$configfile
    
    getHttpRootDirective $configfile Port
    port=$param
    getparam User $configfile $port "Getting User from "
    webowner=$param

    virtnames=`cat $configfile | $awk "
        BEGIN {
            value = \"\"; j=0
        }
        
        { x=0; y=0; server=\"\"; virtname=\"\" }
        
        /^[^#]* *< *[Vv][Ii][Rr][Tt][Uu][Aa][Ll][Hh][Oo][Ss][Tt][ $TAB]/ { 
            virtname = \\\$2; y=1; j++
        }
        
        /^[^#]*[Ss][Ee][Rr][Vv][Ee][Rr][Nn][Aa][Mm][Ee][ $TAB]/  { 
            server = \\\$2; y=2
        }
        
        {
            if (y == 1) {  gsub(/>/,\"\",virtname); ARRAY[j] = virtname }
            if (y == 2) { ARRAY[j] = server }
        }
        
        END { 
            for ( i =1; i <= j; i++ ) { 
                print ARRAY[i] \" \" 
            }
        }"`

    virtnames=`echo $virtnames | sed -e 's/>//g'`
    n=0
    for word in $virtnames 
    do
        n=`expr $n + 1` 
        eval virtwebs$n="$word" 
    done

    while echo
        n=1
        vweb="virtwebs$n"
        val=`eval echo '$'$vweb`
        while [ "$val" != "" ]
        do
            echo "  $n) $val" 
            n=`expr $n + 1`
            vweb="virtwebs$n"
            val=`eval echo '$'$vweb`
        done
        
        echo 
        $echo "Select the virtual web to install (CTRL-D if no more webs): ${nnl}" 
        read virtwebno
    do
        getHttpRootDirective $configfile Port
        port=$param
        until [ "$port" != "" ]
        do
            $echo "Enter the new server's port number:  ${nnl}" 
            read port
        done
        
        port="`eval echo '$'"virtwebs$virtwebno"`:$port"
        
        getHttpVirtualDirective $configfile $port User
        defwebowner=$param
        
        webowner=""
        until [ "$webowner" != "" ]
        do
            $echo "Unix user name of the owner of this new web:[$defwebowner]  ${nnl}"
            read webowner
            if [ "$webowner" = "" ]
            then
                webowner=$defwebowner
            fi
        done
        
        getHttpVirtualDirective $configfile $port Group
        defwebgroup=$param
        
        webgroup=""
        until [ "$webgroup" != "" ]
        do
            echo 
            $echo "Unix group of this new web:[$defgroup]  ${nnl}" 
            read webgroup
            if [ "$webgroup" = "" ]
            then
            webgroup=$defgroup
            fi
        done
        
        webname="/"
        
        admin=""
        until [ "$admin" != "" ]
        do
            $echo "FrontPage Administrator's user name:  ${nnl}" 
            read admin
        done
        
        servertype="apache-fp"
        
        multihost="`eval echo '$'"virtwebs$virtwebno"`"
        if [ "$configfile" = "" ]
        then
            configfile="."
        fi
        
        PORT=$port
        echo "Installing virtual root web into port $port..." 
        echo 
        installserver $port $multihost $webname $webowner $webgroup \
        $admin $configfile $servertype ||
        {
            echo "ERROR:  $webname installation failed." 
            $echo "Hit enter to continue${nnl}" 
            read continue
            return $retval
        }
        
        weconfigfile=""
        
        installnewsubwebs $PORT || error     # Install new servers
        echo
    done
    
    return $retval
}

# Install all subwebs, including per-user webs
installnewsubwebs()
{
    port=$1
    
    retval=0
    
    echo 
    myprompt 'yYnN' "Install new sub/per-user webs now (y/n)" "Y"
    if [ $answer = n ] || [ $answer = N ]
    then
        echo "For details on how to upgrade servers manually, please see" 
        echo "the Server Extension Resource Kit (SERK), located at"
        echo "http://www.microsoft.com/frontpage"
        echo
        return $retval
    fi
    echo 
    
    if [ "$weconfigfile" = "" ]
    then
        until [ "$weconfigfile" != "" ] && [ -f $weconfigfile ]
        do
            port=""
            if [ "$port" = "" ]
            then
                cat <<EOF
 
You need to specify which server to install the subweb into.
Examples:
          80
          www.virtual.web:80
 
          where 80 is the port the server is running on.
 
EOF
                $echo "Which server would you like to install the subweb into:  ${nnl}" 
                read port
            fi
            echo 
            case $port in 
              *:*) weconfigfile="${installdir}/${port}.cnf" ;;
                *) weconfigfile="${installdir}/we${port}.cnf" ;;
            esac
        done
    fi
    
    echo "Using FrontPage Configuration File:  ${weconfigfile}"
    echo
    
    servertype="apache-fp"
    configfile=`grep -i "^serverconfig:" $weconfigfile | sed -e '
                s/serverconfig://g
                s/fakeconf.*\///'`
    configfiledir=`dirname $configfile`"/"
    
    getdocroot $weconfigfile ||
    {
        echo "ERROR:  Unable to get DocumentRoot/UserDir"
        return 1
    }
    
    services=${docroot}"/_vti_pvt/services.cnf"
    
    if [ ! -f $services ]
    then
        echo
        echo "ERROR:  The root web must be installed before sub/per-user webs!"
        echo "Document Root:  ${docroot}"
        $echo "Hit enter to continue${nnl}" 
        read continue
        echo
        return $retval
    fi
    
    echo 
    while $echo "Enter the web name (CTRL-D if no more webs): ${nnl}" 
        read webname    
    do
        admin=""
        until [ "$admin" != "" ]
        do
            $echo "FrontPage Administrator's user name:  ${nnl}" 
            read admin
        done
        
        case "$webname" in
            ~*) PERUSER=1
                echo 
                echo "Web $webname is a per-user web" 
                webowner=`echo $webname | sed -e 's/~//'`
                ;;
             *) PERUSER=0
                echo 
                echo "Web $webname is a subweb"  
                webowner=""
                ;;
        esac
        
        defwebowner=`$lsg ${docroot}${service} | $awk ' { print $3}'`
        until [ "$webowner" != "" ]
        do
            echo
            $echo "Unix user name of the owner of this new web:[$defwebowner]  ${nnl}"
            read webowner
            if [ "$webowner" = "" ]
            then
                webowner=$defwebowner
            fi
        done

        getparam Group $configfile $port "Getting Group from "
        defgroup=$param
        webgroup=""
        if [ "$PERUSER" = 1 ]
        then
            getHomedir $webowner
            if [ -d "${homedir}" ]
            then
                webgroup=`$lsg ${homedir} | $awk ' { print $4}'`
            fi
            if [ -d "${homedir}/${userdir}" ]
            then
                webgroup=`$lsg ${homedir}/${userdir} | $awk ' { print $4}'`
            fi
        fi
        
        until [ "$webgroup" != "" ]
        do
            echo 
            $echo "Unix group of this new web:[$defgroup]  ${nnl}" 
            read webgroup
            if [ "$webgroup" = "" ]
            then
                webgroup=$defgroup
            fi
        done
        
        multihost="."
        
        if [ "$configfile" = "" ]
        then
            configfile="."
        fi
        
        if [ "$servertype" = "" ]
        then
            servertype="."
        fi
        
        installserver $port $multihost $webname $webowner $webgroup \
                      $admin $configfile $servertype ||
        {
            echo "ERROR:  $webname installation failed." 
            $echo "Hit enter to continue${nnl}"
            retval=0 
            read continue
        }
        echo
    done
    
    return $retval
}

installserver()
{
    retval=0
    
    webport="$1"
    multihost="$2"
    webname="$3"
    webowner="$4"
    webgroup="$5"
    admin="$6"
    configfile="$7"
    servertype="$8"

    case $webport in
       *:*) multihost=`echo $webport | cut -d: -f1`
            port=`echo $webport | cut -d: -f2`
            ;;
         *) port=$webport
            ;;
    esac
    
    echo 
    echo "installing server " $webname " on port " $port
    
    if [ "$PERUSER" = 1 ]
    then
        user=`echo $webowner | sed -e 's/~//g'`
        echo 
        echo "Will chown per-user web to $user as part of install." 
        echo "Will chgrp per-user web to $webgroup as part of install." 
        chown="-xUser $user -xGroup $webgroup"  
    else
        if [ "$webowner" != "." ]
        then
            echo 
            echo "Will chown web to $webowner as part of install." 
            echo "Will chgrp web to $webgroup as part of install." 
            chown="-xUser $webowner -xGroup $webgroup"
        else
            chown=""
        fi
    fi
    
    if [ "$configfile" != "." ]
    then
        config="-s $configfile"
    else
        config=""
    fi
    
    if [ "$webname" != "/" ]
    then 
        web="-w $webname"
    else
        web=""
    fi

    if [ "$multihost" != "." ]
    then
        ${FPDIR}/bin/owsadm.exe -o install -p $port $web $config -u $admin $chown -m $multihost || retval=1
    else
        ${FPDIR}/bin/owsadm.exe -o install -p $port $web $config -u $admin $chown -m "" || retval=1
    fi
    
    return $retval
}

###############################################################################
#
# The following set of functions are used for reading the webserver's config
# file(s) (i.e. httpd.conf)
#

# take a string and converts it to a regular expression which matches all
# possible case combinations.
#
# String = [Ss][Tt][Rr][Ii][Nn][Gg]
#
getMixedCase() {
    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
                }"`
}

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

    param=""
    if [ "$gdconfigfile" = "" ]
    then
        return 0
    fi
    
    case $port in
      *:*) getHttpVirtualDirective $gdconfigfile $port $directive ;;
        *) getHttpRootDirective $gdconfigfile $directive ;;
    esac
}

# Get the DocRoot and UserDir settings
getdocroot()
{
    weconfigfile=$1
    
    servertype="apache-fp"
    configfile=`grep -i "^serverconfig:" $weconfigfile | sed -e '
                s/serverconfig://g
                s/fakeconf.*\///'`
    
    echo "Getting DocumentRoot and UserDir."
    
    if [ ! -f "$configfile" ]
    then
        echo "$configfile does not exist."
        return 1
    fi
    
    configfiledir=`dirname $configfile`"/"
    
    docroot=""
    resconffile=$configfile
    
    getHttpDirective $configfile ResourceConfig $port
    if [ "$param" != "" ]
    then
        case $param in
            /dev/null) resconffile=$configfile
                ;;
            /*) resconffile=$param  # fully qualified pathname
                ;;
            *)  file=`basename $param`
                resconffile="${configfiledir}${file}"
                ;;
        esac
	if [ ! -f $resconffile ]
	then
	    echo "ERROR:  $resconffile does not exist! Using $configfile instead."
	    resconffile=$configfile
	fi
    else
        resconffile="${configfiledir}srm.conf"
        if [ ! -f $resconffile ]
        then
	    echo "ERROR: No ResourceConfig directive found, add 'ResourceConfig /dev/null' to $configfile"
            resconffile=$configfile
        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

    if [ "${docroot}" = "" ]
    then
        echo "ERROR:  DocumentRoot not defined!"
        return 1
    fi
    
    if [ ! -d "${docroot}" ]
    then
        echo "ERROR:  ${docroot} does not exist!"
        return 1
    fi
    
    echo
    echo "DocumentRoot: ${docroot}"
    
    if [ "${userdir}" = "" ]
    then
        echo "WARNING:  UserDir not defined."
    else
        echo "UserDir: ${userdir}"
    fi
    
    echo
    
    return 0
}

# call either getHttpVirtualDirective or getHttpRootDirective
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
}

# find a directive in a config file that is not part of a virtual host section
getHttpRootDirective()
{
    configfile=$1
    directive=$2
    
    getMixedCase VirtualHost
    virtualhost=${mc_string}
    
    getMixedCase $directive
    
    param=`cat $configfile | $awk "
            /^[^#]* *< *${virtualhost}/,/^[^#]* *< *\/${virtualhost}/ { next }
            /^[^#]* *${mc_string}[ $TAB]/  { print \\\$2 }" | sed -e 's/"//g'` 
            
    return 0
}

# find a directive in a config file that is part of a virtual host section
getHttpVirtualDirective() # from fp_install.sh
{
    configfile=$1
    port=$2
    directive=$3
    
    virtweb=`echo  $port | sed -e 's/:[0-9]*.$//'`
    virtweb=`basename $virtweb`
    
    getMixedCase VirtualHost
    virtualhost=${mc_string}
    
    getMixedCase ServerName
    servername=${mc_string}
    
    getMixedCase $directive
    
    param=`cat $configfile | $awk "
                            BEGIN    { value = \"\"; j=0 }
                                     { x=0; y=0; server=\"\"; virtname=\"\" }
                        /^[^#]* *< *${virtualhost}[ $TAB]/ { 
                            virtname = \\\$2; y=1; j++
                        }
                        /^[^#]*${servername}[ $TAB]/   { 
                            server = \\\$2; y=2
                        }
                        /^[^#]* *${mc_string}[ $TAB]/  {
                            arg = \\\$2; y=3
                        }
                        
                        {
                            if (y == 1) {
                                gsub(/>/,\"\",virtname)
                                VIRTNAMES[j] = virtname
                            }
                            if (y == 2) { SERVERNAMES[j] = server } 
                            if (y == 3) { ARRAY[j] = arg }
                        }
                    
                    END { 
                            for ( i =1; i <= j; i++ ) { 
                                if (SERVERNAMES[i] == \"$virtweb\" || VIRTNAMES[i] == \"$virtweb\" ) {
                                    print ARRAY[i] 
                                }
                            }
                    } " | sed -e 's/"//g'`
    
    if [ "$param" = "" ]
    then
        getHttpRootDirective $configfile $directive
    fi 
}

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

    getDirective "$httpdconfigfile" "$directive" "$port"   # try httpd.conf
    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
    param=`egrep -i "^[ $TAB]*$1[ $TAB]" $2 | $awk '{print $2}'` || return 1
    return 0;
}

###############################################################################
# (formerly a seperate script, change_server.sh)
# these functions are used to replace the existing Apache daemon (httpd) with a
# new one that contains the FrontPage patch

change_server()
{
    rm -f ${FPDIR}/apache-fp/suidkey
    
    ps=`$psea | tail -10` ; echo $ps | sed -e 's/ //g' | cut -c10-137 > ${FPDIR}/apache-fp/suidkey
    
    chown root ${FPDIR}/apache-fp/suidkey
    chmod 600 ${FPDIR}/apache-fp/suidkey

    echo
    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 
    
    upgradeHttpd || 
    {
        echo "ERROR:  Unable to upgrade Apache daemon!"
        return 1
    }
    
    return 0
}

# run "strings" on the httpd file to see if the current version of the FP patch
# is installed; ask the user if they want to upgrade to the current one
checkVersion()
{
    rtc=0;
    echo
    NEWHTTPD=$NEWHTTPDNEW
    
    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
}

# Replace the old httpd daemon with the new httpd daemon (after making backup)
upgradeHttpd()
{
    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
    }
    
    return 0
}

main
