#! /bin/sh

CONFIGS="agents bcnunet bcnulocal hostinfo"
SAVED="custom agent bin etc cgi-bin scripts platform"
USAGE="upgrade_bcnu -h [ bcnu_home_dir ] -s save -a automatic"

while getopts h:sa x
do
        case $x in
        h)      BCNUHOME=$OPTARG;;
        s)      saved=1;;
        a)      automatic=1;;
        \?)     echo "upgrade_bcnu : syntax error "
                echo $USAGE
                exit 2;;
        esac
done

if [ -z "$BCNUHOME" ]
then

if [ -d /usr/local/bcnu ]
then
        BCNUHOME="/usr/local/bcnu"
else
        echo "Enter directory name of CURRENT bcnu home: \c"
        read home
        if [ -z "$home" ]
                then
			echo "Upgrade aborted"
                      exit
                else
  	              BCNUHOME=$home
        fi
fi
fi

DIRNAME=`dirname $BCNUHOME`

if [ -d $BCNUHOME ]
then
	:
else
	echo "$BCNUHOME does not exist : Upgrade aborted"
        exit
fi

mkdir /tmp/bcnuetc 2>/dev/null
cd $BCNUHOME/etc
cp $CONFIGS /tmp/bcnuetc 2>/dev/null

if [ -f $BCNUHOME/etc/bcnud.pid ]
	then
		echo "Stopping bcnud"
		$BCNUHOME/etc/bcnud_server stop
fi

cd $BCNUHOME

. $BCNUHOME/etc/bcnuenv

BCNU="$BCNUHOME/bin/bcnu -s $BCNUPORT"

echo "Retrieving client file from : $BCNUHOST"
if $BCNU -a get -f bcnuclient.tar.Z $BCNUHOST >/tmp/bcnuclient.tar.Z
	then
		echo "Client retrieved OK"
else
		echo "Retrieve Failed - Upgrade aborted"
		exit
fi

cd $DIRNAME

if [ -z "$saved" ]
then
	echo "Do you want to save the existing bcnu installation $BCNUHOME? y/n \c"
	read yorn
else
        yorn="y"
fi
if [ "n" = "$yorn" ]
	then
		echo "Removing $BCNUHOME"
		rm -r $BCNUHOME
	else
		echo "Saving $BCNUHOME to /tmp/bcnusaved.tar.Z"
		cd $BCNUHOME
		tar cf /tmp/bcnusaved.tar $SAVED
		compress /tmp/bcnusaved.tar
fi

cd $DIRNAME

if [ -z "$automatic" ]
then

	echo "About to install bcnu to $DIRNAME/bcnu Do you want to continue? y/n \c"
	read yorn
else
	yorn="y"
fi
if [ "n" = "$yorn" ]
	then
		echo "Upgrade aborted"
		exit
	else
		echo "Untarring files" 
		zcat /tmp/bcnuclient.tar.Z | tar xf -
fi

echo "Upgrade preparation complete - starting client install"
cd bcnu

scripts/client_install -h $BCNUHOME -c $BCNUSERVER -d y -s y -l y

echo "Copying the files ($CONFIGS) to the etc directory"
cd $BCNUHOME/etc
cp /tmp/bcnuetc/$CONFIGS .

{
rm /tmp/bcnuclient.tar.Z
rm -r /tmp/bcnuetc
} 2>/dev/null

echo "Upgrade process complete - check etc/agents for updates"
