#!/bin/sh -e


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


check_mod()
{
	mod=$1 ; shift
	own=$1 ; shift

	echo "Checking file or directory $@ for mod $mod and owner $own"
	if [ -d "$@" -o -f "$@" ] ; then
		chmod $mod "$@"
		chown $own "$@"
	fi
}

check_exist()
{
	what=$1 ; shift
	mod=$1 ; shift
	own=$1 ; shift

	case $what in
		-f)
			echo "Checking if file $@ exists"
			[ ! -f "$@" ] && mkdir -p "${@%/*}" && touch "$@"
			;;
		-d)
			echo "Checking if directory $@ exists"
			[ ! -d "$@" ] && mkdir -p "$@"
			;;
		*)
			;;
	esac
	check_mod $mod $own $@
}


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


post_install()
{
	SVC="yandex-solomon-backup"

	DIR="/Berkanavt/solomon-backup"
	GROUP_DIR="/etc/yandex"
	GROUP_SCRIPT="/Berkanavt/solomon-backup/scripts/group_update.sh"

	check_exist -d 755 root:root $GROUP_DIR
	for D in backup logs tmp ; do
		check_exist -d 755 user_backup:group_solomon ${DIR}/$D
	done
	check_exist -f 755 root:root $GROUP_SCRIPT

	$GROUP_SCRIPT

	if [ -x /bin/systemctl -a -f /etc/systemd/system/${SVC}.service ] ; then
		if ! /bin/systemctl daemon-reload ; then
			echo "Cannot reload ${SVC} systemd configuration!"
		fi
		if ! /bin/systemctl enable ${SVC} ; then
			echo "Cannot enable ${SVC} service!"
		fi
		echo "Restarting ${SVC}"
		if ! /bin/systemctl restart ${SVC} ; then
			echo "Cannot restart ${SVC} service!"
		fi
	elif [ -x /usr/bin/service -a -f /etc/init/${SVC}.conf ] ; then
		echo "Restarting ${SVC}"
		if ! /usr/bin/service ${SVC} restart ; then
			echo "Cannot restart ${SVC} service!"
		fi
	fi
}


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


case "$1" in
	configure)
		post_install
	;;

	abort-upgrade|abort-remove|abort-deconfigure)
	;;

	*)
		echo "postinst was called with unknown argument '$1'" >&2
		exit 1
	;;
esac

#DEBHELPER#

exit 0
