#!/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()
{
	MYPMMCNF="/Berkanavt/keys/pmm.cnf"
	SECRETSFILE="/Berkanavt/keys/graphite/mysql.secrets"

	check_exist -f 400 nobody:nogroup $MYPMMCNF

	if [ -r $SECRETSFILE ] ; then
		EXPORTER_PASS="`awk -vFS=':' '/^exporter:/ {print $2}' $SECRETSFILE`"
		sed -i "s/EXPORTER_PASS/$EXPORTER_PASS/" $MYPMMCNF
	else
		echo "No $SECRETSFILE, cannot set password!"
	fi

	service grafanamon restart
	service yandex-solomon-agent restart
}


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


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
