#!/bin/sh

shortname=$(basename "$0")
scriptname="$0"
case "$scriptname" in
	/*) ;;
	*) scriptname="$(pwd)/$0" ;;
esac
rootdir="$(cd "$(dirname "$scriptname")" >/dev/null 2>&1 && pwd)"
rootdir=$(dirname "$rootdir")

PROD=ftscan

is_systemd_os()
{
	systemctl > /dev/null 2>&1
	if [ $? -eq 0 ]; then
		return 0
	else
		return 1
	fi
}

install_service()
{
	is_systemd_os
	if [ $? -eq 0 ]; then
		cp "$rootdir/doc/$PROD.service" /etc/systemd/system &&
			systemctl daemon-reload &&
			systemctl enable $PROD &&
			systemctl start $PROD
		if [ $? -ne 0 ]; then
			echo "Install and run service"
			return 5
		fi
		return 0
	fi

	# for non-systemd OS just return OK
	return 0
}

uninstall_service()
{
	is_systemd_os
	if [ $? -eq 0 ]; then
		systemctl stop $PROD
		systemctl disable $PROD
		rm /etc/systemd/system/$PROD.service
		systemctl daemon-reload
		return 0
	fi

	# for non-systemd OS just return OK
	return 0
}

do_install()
{
	install_service
	if [ $? -eq 0 ]; then
		echo "Installed successfully"
		return 0
	else
		echo "Error occured during installation"
		return 1
	fi
}

do_uninstall()
{
	uninstall_service > /dev/null 2>&1
	echo "Uninstalled successfully"
}

whoami=`id -u`
if [ "$whoami" = "" ]; then
	echo "cannot determine user" >&2
	exit 1
fi
if [ $whoami -ne 0 ]; then
	echo "Run this script under root user" >&2
	exit 1
fi

TEMP=$(getopt -o 'iu' --long 'install,uninstall' -n "$shortname" -- "$@")

if [ $? -ne 0 ]; then
	echo 'Invalid arguments' >&2
	exit 1
fi

eval set -- "$TEMP"
unset TEMP

iflag=0
uflag=0

while true; do
	case "$1" in
		'-i'|'--install')
			iflag=1
			shift
			continue
		;;
		'-u'|'--uninstall')
			uflag=1
			shift
			continue
		;;
		'--')
			shift
			break
		;;
		*)
			echo 'Invalid argument' >&2
			exit 1
		;;
	esac
done

if [ $iflag -eq 0 -a $uflag -eq 0 -o $iflag -eq 1 -a $uflag -eq 1 ]; then
	echo "One of install or uninstall should be specified" >&2
	exit 1
fi

if [ $iflag -eq 1 ]; then
	do_install
else
	do_uninstall
fi
exit $?
