#!/bin/sh
# BLURB gpl
#
#			Coda File System
#			    Release 6
#
#	    Copyright (c) 1987-2016 Carnegie Mellon University
#		    Additional copyrights listed below
#
# This  code  is  distributed "AS IS" without warranty of any kind under
# the terms of the GNU General Public Licence Version 2, as shown in the
# file  LICENSE.  The  technical and financial  contributors to Coda are
# listed in the file CREDITS.
#
#			Additional copyrights
#			   none currently
#*/

prefix=/usr
exec_prefix=${prefix}

echon() {
    if [ "$(echo -n)" = "-n" ] ; then
	echo "$@"'\c'
    else
	echo -n "$@"
    fi
}

#
# arguments
#
if [ $# != 0 ] ; then
    echo "Usage: $0"
    exit 1
fi

#
# Greeting!
#

echo "Welcome to the Coda Server Setup script!"
echo

if [ "$(uname -s)" != Linux ] ; then
    domain=""
    while [ "$domain" = "" ] ; do
	echon "What is the domain name for your servers? "
	read -r domain
    done
    hn=$(hostname -s).$domain
    export domain
else
    hn=$(hostname -f)
fi
export hn

#
# initial information
#
conf="$(${exec_prefix}/sbin/codaconfedit server.conf)"
if [ "$conf" != /dev/null ] ; then
    yesno=""
    echo "You already have a file $conf!"
    echo "Continuing will remove that file."
    while [ "$yesno" = "" ]; do
	echon "Do you want to continue? [yes/no] "
	read -r yesno

        case "$(echo "$yesno" | tr '[:upper:]' '[:lower:]')" in
        y|yes) ;;
        n|no) echo "Not configuring a coda server!" ; exit 1 ;;
        *) yesno="" ; echo "Please answer yes or no." ;;
	esac
    done
    if ! rm "$conf" ; then
	echo "Could not remove $conf.  Exiting."
	exit 1
    fi
fi

#
# Configuration directories:
#
echo 'Setting up config files for a coda server.'

# figure out where the server.conf template, and thus the new server.conf
# file are located.
conf_template="$("${exec_prefix}/sbin/codaconfedit" server.conf.ex)"
if [ "$conf_template" = /dev/null ] ; then
    echo "Could not find the server.conf.ex template file"
    exit 1
fi
conf_directory=$(dirname "$conf_template")
conf="$conf_directory/$(basename "$conf_template" .ex)"

echon "What is the root directory for your coda server(s)? [/vice] "
vicedir=""
read -r vicedir

if [ "$vicedir" = "" ] ; then
    vicedir=/vice
fi

"${exec_prefix}/sbin/codaconfedit" server.conf vicedir "$vicedir"
#
# server.conf standard
#
"${exec_prefix}/sbin/codaconfedit" server.conf rvmtruncate 5
"${exec_prefix}/sbin/codaconfedit" server.conf trace 100


echo "Setting up $vicedir."

for i in auth2 backup db misc vol/remote srv ; do
    mkdir -p "${vicedir}/$i"
done

echo "Directories under $vicedir are set up."
echo

#
# Setup .../db
#
cd "$vicedir/db" || exit

#
# Ask about scm and tokens....
#
yesno=""
while [ "$yesno" = "" ]; do
    echon 'Is this the master server, aka the SCM machine? (y/n) '
    read -r yesno

    case "$(echo "$yesno" | tr '[:upper:]' '[:lower:]')" in
    y|yes) isscm=Y ;;
    n|no)  isscm=N ;;
    *) yesno="" ; echo "Please answer yes or no." ;;
    esac
done

if [ "$isscm" = N ]; then
    until [ "$scmhost" != "" ]; do
	echon "Enter the hostname of the SCM machine : "
	read -r scmhost
    done
    echo "$scmhost" > scm

    token=""
    until [ "$token" != "" ]; do
	echon "Enter the update token that matches SCM $scmhost: "
	read -r token
    done

    rm -f update.tk
    touch update.tk
    chmod 600 update.tk
    echo "$token" >> update.tk

    if ! "${exec_prefix}/sbin/updatefetch" -h "$scmhost" -r db/servers -l servers ; then
	echo "Could not contact SCM."
	echo "Check whether the updatesrv process is running on the SCM."
	exit 1
    fi

    echo "Fetching needed files from SCM $scmhost."
    for which in auth2.pw auth2.tk auth2.lock prot_users.cdb volutil.tk files
    do
	if ! "${exec_prefix}/sbin/updatefetch" -h "$scmhost" -r "db/$which" -l "$which" ; then
	    echo "Could not fetch $which from SCM.  Make sure SCM is setup"
	    echo "correctly and then rerun $0."
	    exit 1
	fi
    done
    # non critical files
    for which in ROOTVOLUME
    do
	"${exec_prefix}/sbin/updatefetch" -h "$scmhost" -r "db/$which" -l "$which" 2>/dev/null || true
    done
    echo "Done."

else

    echo
    echo "Setting up tokens for authentication."

    for which in update auth2 volutil; do
	token=""
	until [ "$token" != "" ]; do
	    echo "The following token must be identical on all servers."
	    echon "Enter a random token for $which authentication : "
	    read -r token
	done

	rm -f "$which.tk"
	touch "$which.tk"
	chmod 600 "$which.tk"
	echo "$token" >> "$which.tk"
    done
    echo tokens done!

    touch auth2.lock

#
# files file for update
#

    echo
    echo Setting up the file list for update client
    cat > "${vicedir}/db/files" <<EOF
auth2.pw
auth2.tk
auth2.tk.BAK
auth2.lock
files
prot_users.cdb
servers
scm
update.tk
volutil.tk
VLDB
VRDB
VRList
maxgroupid
EOF

    echo Filelist for update ready.
fi

# add a couple of empty files to avoid updateclnt problems
for f in auth2.tk.BAK VLDB VRDB VRList ; do
    if [ ! -f "${vicedir}/db/$f" ]; then
	touch "${vicedir}/db/$f"
    fi
done

#
# startup scripts
#
case "$(uname)" in
  *BSD)
    yesno=""
    while [ "$yesno" = "" ]; do
	echon 'Do you want to start the server at boot time? (y/n) '
	read -r yesno

        case "$(echo "$yesno" | tr '[:upper:]' '[:lower:]')" in
        y|yes)
            touch ${vicedir}/srv/STARTFROMBOOT
            grep "/usr/etc/rc.vice" /etc/rc.local > /dev/null 2>&1
            if [ $? != 0 ]; then
                echo "if [ -x \"/usr/etc/rc.vice\" ]; then \"/usr/etc/rc.vice\" start ; fi" >> /etc/rc.local
            fi
            echo "Startup scripts now installed."
            ;;
        n|no)
            echo "You will have to start your coda server by hand."
            ;;
        *) yesno="" ; echo "Please answer yes or no." ;;
        esac
    done
    ;;
esac

#
# ${vicedir}/hostname
#
echo "$hn" > "$vicedir/hostname"

#
# Check whether codatunnel should be enabled (Satya, 2019-12-27)
#
yesno=""
while [ "$yesno" = "" ]; do
    echon "Would you like codatunnel enabled? [yes/no] "
    read -r yesno

    case "$(echo "$yesno" | tr '[:upper:]' '[:lower:]')" in
    y|yes) "${exec_prefix}/sbin/codaconfedit" server.conf codatunnel 1 ;;
    n|no)  "${exec_prefix}/sbin/codaconfedit" server.conf codatunnel 0 ;;
    *) yesno="" ; echo "Please answer yes or no." ;;
    esac
done

#
# end of common setup area, now specialize to scm or non scm
#
if [ "$isscm" = Y ]; then
    echo  "Now installing files specific to the SCM..."
    # files.export ...
    echo "db" > "$vicedir/db/files.export"
    while read -r n ; do
      echo "db/$n" >>  "$vicedir/db/files.export"
    done < "$vicedir/db/files"
    if ! ( "${exec_prefix}/sbin/vice-setup-scm" && "${exec_prefix}/sbin/vice-setup-user" && \
	   "${exec_prefix}/sbin/vice-setup-rvm" && "${exec_prefix}/sbin/vice-setup-srvdir" ) ; then
	echo "Your coda server is not completely setup.  You will need"
	echo "set it up by hand or fix the problems and rerun $0."
	exit 1
    fi
    DP=$(awk '{print $2}' "$vicedir/db/vicetab" | head -n 1)
    echo "Congratulations: your configuration is ready..."
    echo

    start=""
    yesno=""
    while [ "$yesno" = "" ]; do
	echon 'Shall I try to get things started? (y/n) '
	read -r yesno

        case "$(echo "$yesno" | tr '[:upper:]' '[:lower:]')" in
        y|yes) start=Y ;;
        n|no) echo "Here is what you would have to execute to get things up and running" ;;
        *) yesno="" ; echo "Please answer yes or no." ;;
        esac
    done

    set -e
    echo " auth2        - Coda authentication server"
    [ "$start" ] && "${exec_prefix}/sbin/auth2"
    echo " updatesrv    - Coda update server"
    [ "$start" ] && "${exec_prefix}/sbin/updatesrv"
    echo " updateclnt   - Coda update client"
    [ "$start" ] && "${exec_prefix}/sbin/updateclnt"
    echo " startserver  - Coda file server"
    [ "$start" ] && ( "${exec_prefix}/sbin/startserver" || echo "Failed to start the Coda server" )
    echo

    if [ "$start" ] ; then
	echo
	echo "Nice, it looks like everything went ok"
	echo "Now I'll try to create an initial root volume"
    fi

    echo " createvol_rep / $hn$DP   - create initial root volume"
    [ "$start" ] && "${exec_prefix}/sbin/createvol_rep" / "$hn$DP"

    if [ "$start" ] ; then
	echo
	echo "That seems to have worked..."
	echo "If you have a working Coda client you should now be able to"
	echo "access the new Coda realm"
	echo " - cfs lv /coda/$hn/"
    fi
    echo
    echo "enjoy Coda."
    echo " for more information see http://www.coda.cs.cmu.edu."

    exit 0
fi

#
# specifics for non SCM servers only
#
echo  "Now installing things specific to non-SCM machines..."

if ! ( "${exec_prefix}/sbin/vice-setup-rvm" && "${exec_prefix}/sbin/vice-setup-srvdir" ) ;  then
    echo "Your coda server is not completely setup.  You will need"
    echo "set it up by hand or fix the problems and rerun $0."
    exit 1
fi

scm=$(cat $vicedir/db/scm)
echo "You have set up $(cat "$vicedir/hostname")"
echo "Your SCM is $scm"
echo "Other config files will be fetched from the SCM by updateclnt."
echo
echo "To finish your server setup you should start the update and"
echo "authentication daemons:"
echo
echo "      updateclnt"
echo "      auth2"
echo
echo "After that, there is still some configuration needed on the SCM before"
echo "this server can be started."
echo
echo "An entry for this host is needed in /vice/db/servers"
echo "Then all servers need to be shut down and restarted, as they need to"
echo "learn about the existence of the new server."
echo "After all that it _should_ be ok to start the new server and create"
echo "your first replicated volume."
#echo " On the SCM ($scm) run: new_server $hn"
#echo
#echon "Now you can "
#echo
#echo " start the fileserver: startserver &"
