#!/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()
{
	# reload configs
	initctl reload-configuration
	sleep 1


	# restart monitor only if it is started
	srv="graphitemon"
	if status $srv | grep -q "$srv start" ; then
		srv_restart $srv
	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
