#!/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="mega-graphite-web"
	DIR="/Berkanavt/mega-graphite"

	# compile
	pycompile $DIR/web/webapp/graphite


	#if [ -z "$2" ] ; then
	# called on clean install. We have to initialize graphite-web db.
	#	export PYTHONPATH=$PYTHONPATH:$DIR/web/webapp/
	#	export LANG="en_US.UTF-8"
	#	echo "no" | django-admin.py syncdb --settings=graphite.settings
	#else
	# called on upgrade.
	#	echo "yes"
	#fi


	# new config -> restart memcached
	#service memcached restart


	# nginx configuration
	GCONF="/etc/nginx/sites-enabled/10-graphite-ch.conf"
	rm -f "$GCONF"
	ln -s "../sites-available/10-graphite-ch.conf" "$GCONF"
	echo "CONFFILE=/etc/nginx/nginx-default.conf" > /etc/default/nginx

	# check owners
	USER=user_mgweb
	USER_STORAGE=user_mgstorage
	GROUP=group_solomon
	if /usr/bin/id $USER >/dev/null 2>&1 ; then
		if [ -d "$DIR/logs" ] ; then
			chgrp -R $GROUP $DIR/logs
			check_mod 775 $USER:$GROUP $DIR/logs
			find $DIR/logs -not -user $USER -and -not -user $USER_STORAGE -exec chown $USER:$GROUP {} \+
		fi
		if [ -d "/var/run/graphite" ] ; then
			chown -R $USER:$GROUP /var/run/graphite
			chmod 775 /var/run/graphite
		fi
		if [ -d "$DIR/web" ] ; then
			chown -R $USER:$GROUP $DIR/web
		fi
	else
		echo "ACHTUNG! No such user $USER!"
	fi

	# regenerate local settings
	$DIR/web/etc/regenerate_local_settings.sh

	# reload configs
	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!"
		fi
		if ! /bin/systemctl restart ${SVC} ; then
			echo "Cannot restart ${SVC} service!"
		fi
	elif [ -x /usr/sbin/service -a -f /etc/init/${SVC}.conf ] ; then
		initctl reload-configuration
		sleep 1
		if ! /usr/sbin/service ${SVC} restart ; then
			echo "Cannot restart ${SVC} service!"
		fi
	fi

	# reload nginx
	service nginx status && service nginx reload
}


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


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
