#!/bin/bash

. ${TOOLKIT}-functions.sh

server_url=$(jtconf glpi-agent.server_url)
tasks=$(jtconf glpi-agent.tasks)


# XXX
# XXX this should be moved in kusa-functions.sh
# XXX
enable_service()
{
	local svc=$1
	local inifile="/etc/init.d/$svc"
	local lvl=
	local here=$(pwd)

	[ -f $inifile ] || {
		echo "enable_service(): can't enable service '$svc'" >&2
		echo "enable_service(): $inifile doesn't exists" >&2
		return 1
	}

	which insserv >/dev/null && {
		insserv -v $inifile || return $?
		return 0
	}

	# insserv not available, manually search for levels in inifile
	# assuming conservative priority, last start (8) and early kill (2)
	#
	grep -q '^# Default-Stop:' $inifile || {
		echo "enable_service(): can't enable service '$svc'" >&2
		echo "enable_service(): error, $inifile doesn't contain Default-Stop tag" >&2
		return 1
	}
	grep -q '^# Default-Start:' $inifile || {
		echo "enable_service(): can't enable service '$svc'" >&2
		echo "enable_service(): error, $inifile doesn't contain Default-Start tag" >&2
		return 1
	}

	rm -f /etc/rc*.d/[KS][0-9][0-9]$svc

	for lvl in $(grep '^# Default-Stop:' $file | sed -e 's/.*Stop://')
	do
		cd /etc/rc$lvl.d
		ln -s ../init.d/$svc K02$svc
	done
	for $lvl in $(grep '^# Default-Start:' $file | sed -e 's/.*Start://')
	do
		cd /etc/rc$i.d
		ln -s ../init.d/$svc S08$svc
	done

	cd "$here"
	return 0
}


# (MAIN)

# this is missing from veeam packages
#
enable_service veeamservice

# FIRST RUN?
#
# - install our custom cfg file
# - create default repository
# - create default job
#
file="ku-veeam.cfg"

# instead of automatically install our config file (from 'install' file)
# we install it manually, so we can use his existence to know if it is
# a fresh veeam installation
#
if [ -f /etc/veeam/$file ]
then
	# exists, but we install it anyway (needs to keep updated)
	installfile $file /etc/veeam/ root:root 660
else
	# do not exists, is a fresh veeam installation
	installfile $file /etc/veeam/ root:root 660

	echo -e "\n\tYOU NEED TO ACCEPT VEEAM LICENCE BEFORE PROCEED\n"
	confirm
	veeam

	veeam_create_default_repo
	veeam_create_default_job
fi



# cleanup
#
uninstallfiles --remove \
	/usr/sbin/veeam_add_default_job \
	/usr/sbin/veeam_run_default_job


$SOMETHING_CHANGED && {
	restart_service veeamservice veeamservice
}

exit 0
