#!/bin/sh


set -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() {
	check_exist -d 700 root:root /etc/nginx/ssl
	chmod 400 /etc/nginx/ssl/*


	ENVFILE="/etc/solomon/env"
	ND="/etc/nginx"
	SE="$ND/sites-enabled"
	SA="$ND/sites-available"
	CONF="grafana"
	CONFFILE="$ND/nginx-grafana.conf"
	NGINX_DEFAULTS="/etc/default/nginx"

	echo "CONFFILE=$CONFFILE" > $NGINX_DEFAULTS
	echo "ulimit -n 16384" >> $NGINX_DEFAULTS

	# setup grafana, update group
	for SC in /usr/local/bin/grafana_setup.sh /usr/local/bin/group_update.sh ; do
		check_mod 755 root:root $SC
		$SC
	done

	if [ -r $ENVFILE ] ; then
		e=$(cat $ENVFILE 2>/dev/null)

		if [ "$e" != "testing" -a "$e" != "production" ] ; then
			echo "Cannot determine environment"
			exit 1
		else
			if [ $e = "testing" ] ; then
				echo "Test environment"
				sed -Ei 's/execute_alerts .+$/execute_alerts = false/; s/grafana\.yandex-team\.ru/grafana-dev\.yandex-team\.ru/' /etc/grafana/grafana.ini
			fi

			ln -svf $SA/$CONF $SE/$CONF

			if which nginx >/dev/null && nginx -qt -c $CONFFILE ; then
				nginx -s reload -c $CONFFILE
			else
				echo "Ningx configuration failed"
			fi
		fi
	fi

	/bin/systemctl daemon-reload
	for APP in yandex-solomon-agent grafana-redirector ; do
		if [ -x /bin/systemctl -a -f /etc/systemd/system/${APP}.service ] ; then
			if ! /bin/systemctl enable ${APP} ; then
				echo "Cannot enable ${APP} service!"
			fi
			if ! /bin/systemctl restart ${APP} ; then
				echo "Cannot restart ${APP} service!"
			fi
		fi
	done

	TUNUP="/usr/lib/yandex-netconfig/ya-slb-tun"
	if [ -x $TUNUP ] ; then
		$TUNUP restart
	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
