# /bin/bash


# --------------------------------------------------------------
#
# Installs pggibs.
#
# Author:  Zlatko Michailov
# Created: 11-Jun-2004
# Updated: 17-Jun-2004
# Updated: 22-Jun-2004
#
# --------------------------------------------------------------



parseOptions()
{
	for opt
	do
		if [[ "$opt" == "--help" ]]
		then
			optHelp="$opt"

		elif [[ "$opt" == "--force" ]]
		then
			optForce="$opt"
		fi
	done
}



help()
{
	echo "install [--help | --force]"
	echo "Installs pgjobs - job scheduling and executing mechanism for PostgreSQL."
	echo "Copyright (c) 2003-2004, Zlatko Michailov"
	ext="1"
}



confirm()
{
	cfrm=""

	if [[ "$optForce" != "" ]]
	then
		cfrm="y"
	else
		read -p "$1 (Y/N)? " -n 1 ans
		echo ""

		if [[ "$ans" == "y" || "$ans" == "Y" ]]
		then
			cfrm="y"
		fi
	fi
}



initEnvironment()
{
	etcDir="/etc/init.d"
	appDir="/usr/share/pgjobs"
	distribDir=`echo $0 | gawk '{ print gensub( "/install", "", "g" ) }'`

	oldVersion=""
	if [[ -a $appDir/pgjobs.conf ]]
	then
		oldVersion=`grep -o '^system=[[:digit:].]*' $appDir/pgjobs.conf | gawk -F '=' '{print$2}'`
	fi

	newVersion=`grep -o '^system=[[:digit:].]*' $distribDir/pgjobs.conf | gawk -F '=' '{print$2}'`
}



baseInstall()
{
	if [[ -a $appDir ]]
	then
		rm -rf $appDir
	fi

	mkdir $appDir
	chmod 777 $appDir

	cp -f $distribDir/app/*			$appDir
	cp -f $distribDir/etc/*			$etcDir
	cp -f $distribDir/pgjobs.conf	$appDir

	chmod 666 $appDir/pgjobs.conf

	/sbin/chkconfig --add pgjobs
}



upgradeInstall()
{
	echo

	# There may be an agent still running. Stop it.
	$etcDir/pgjobs stop


	# Incremental upgrades consist of units of the following
	# type, put in ASCENDING order of the version:
	#
	# if [[ "$oldVersion < "x.xx.xx" ]]
	# then
	#	... incremental statements ...
	# fi


	# Start the agent
	$etcDir/pgjobs start
}



install()
{
	confirm "Do you want to install pgjobs"
	if [[ "$cfrm" != "" ]]
	then
		initEnvironment
		if [[ "$oldVersion" < "$newVersion" ]]
		then
			echo "$oldVersion <- $newVersion"
			if [[ "$oldVersion" == "" ]]
			then
				baseInstall
			fi

			upgradeInstall
		else
			echo "Nothing to do."
			echo "The version you are trying to install, $newVersion, is older"
			echo "than the version that is already installed, $oldVersion."
			ext="2"
		fi
	else
		ext="3"
	fi
}


# --------------------------------------------------------------

exit="0"
echo ""

parseOptions $*
if [[ "$optHelp" != "" ]]
then
	help
else
	install
fi

echo ""
exit $ext


