#!/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()
{
	CRT="/etc/mysql/root.crt"
	CONF="/usr/local/etc/mysql-balancer.conf"
	SVC="mysql-balancer"
	ENVFILE="/etc/solomon/env"

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

		if [ "$e" != "testing" -a "$e" != "production" ] ; then
			echo "Cannot determine environment"
		else
			if [ $e = "testing" ] ; then
				echo "Test environment [grafana]"
				ln -svf ${CONF}.dev $CONF
			else
				if hostname | grep -q grafana ; then
					echo "Production environment [grafana]"
					ln -svf ${CONF}.prod $CONF
				else
					echo "Production environment [graphite]"
					ln -svf ${CONF}.mg $CONF
				fi
			fi
		fi
	fi
	check_exist -d 755 root:root /etc/mysql

	# Fetch root CA
	wget "https://crls.yandex.net/allCAs.pem" -O $CRT
	check_mod 440 root:root $CRT

	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
