#!/bin/sh


set -e


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


install_conf()
{
	echo "Installing configuration file: $1"
	[ -s "$1" -a ! -f "$1.BACKUP" ] && cp -f "$1" "$1.BACKUP"
	[ -f "$1.yandex" ] && cp -f "$1.yandex" "$1"
}

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 $@
}

srv_restart()
{
	for s in $@; do
		echo "Stopping service $s"
		service $s stop
	done
	sleep 1
	for s in $@; do
		echo "Starting service $s"
		service $s start
	done
}


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


post_install()
{
	SVC="nginx"
	DIR="/Berkanavt/nginx"
	check_exist -d 775 www-data:adm $DIR/logs


	# wait for upstart
	sleep 1

	# restart services
	srv_restart rsyslog


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


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


case "$1" in
	configure)
		post_install || true
	;;

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

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

#DEBHELPER#

exit 0
