#!/bin/bash
#

INST_CAMEO=/Cameo
INST_BKP=$INST_CAMEO/bkp

TMP=/tmp/tmp.reversion

OSPROGS="gzip rsync sort ssh ssh-keygen openssl"
OSPATH="/usr/sbin /usr/bin /sbin /bin"

dte=$(date '+%Y-%m-%d.%H-%M-%S')

rm -f $TMP.*
exit_es=0

echo
echo
echo

if [ -d $INST_CAMEO ]; then
	mkdir -p $INST_CAMEO

	echo "Stopping Reversion"
	systemctl stop reversion
	
	# Archive the old version
	export CPIOFN=$INST_CAMEO/bkp-$dte.cpio
	wd=$($CWD)
	cd $INST_CAMEO
	mv bkp bkp-$dte
	find bkp-$dte | cpio -oc > $CPIOFN
	mv bkp-$dte bkp
	cd "$wd"
else
	mkdir "$INST_CAMEO";
fi

echo "Extracting software"
cd $INST_CAMEO
tar xpf bkp.tar 

echo "Configuring /etc/Cameo"
if [ ! -d /etc/Cameo ]; then
	mkdir -p /etc/Cameo
fi
echo "$INST_BKP" > /etc/Cameo/bkproot
cp $INST_BKP/rls/etc_Cameo_bashrc.rls /etc/Cameo/bashrc
cp $INST_BKP/rls/in.revsrvd.rls /etc/Cameo/in.revsrvd
cp $INST_BKP/rls/revdaemons.rls /etc/Cameo/revdaemons
chmod 440 /etc/Cameo/bkproot
chmod 440 /etc/Cameo/bashrc
chmod 550 /etc/Cameo/in.revsrvd
chmod 550 /etc/Cameo/revdaemons

a=$($INST_BKP/bin/bkp_arch)

echo "Creating links:"
for osp in $OSPROGS
do
	found=n
	for pth in $OSPATH
	do
		fn="$pth/$osp"
		if [ -x "$fn" ]; then 
			
			rm -f "$INST_BKP/bin.$a/$osp"

			cmd="ln -s $fn $INST_BKP/bin.$a/$osp"
			echo "   $cmd"
			eval $cmd
			found=y
			break
		fi
	done
	if [ "$found" == n ]; then
		echo "	$osp" >> $TMP.missing
	fi
done

if [ -f "$TMP.missing" ]; then
	echo 
	echo "** The Following system executables were not found:"
	echo
	cat $TMP.missing
	echo
	echo "** Reversion functionality may be impaired."
	echo
	exit_es=1
fi

echo "Update /etc/services"
listed=$(awk '{print $2}' /etc/services | grep '5842/tcp')
if [ "$listed" == "" ]; then
	grep -v '5842/tcp' /etc/services > $TMP.services
	cp $TMP.services /etc/services
	echo "reversion 5842/tcp" >> /etc/services
fi

echo "Update xinetd"
if [ ! -d /etc/xinetd.d ]; then
	mkdir -p /etc/xinetd.d/
fi
cp $INST_BKP/rls/xinetd.conf.rls /etc/xinetd.d/reversion
chmod 400 /etc/xinetd.d/reversion

echo "Update startup script"
cp $INST_BKP/rls/init_d_reversion.rls /etc/init.d/reversion
chmod 700 /etc/init.d/reversion
systemctl enable reversion

echo "Restart xinetd"
/etc/init.d/xinetd restart

echo "Restart Reversion daemons"
systemctl start reversion

echo "Finished"
echo

rm -f $TMP.*
exit $exit_es
