#!/bin/sh -ex


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 $@
}

enable() {
	local _app

	DISCOVERY_DIR="/Berkanavt/solomon/discovery"
	UNI_DIR="/var/run/unified_agent"
	UNI_CACHE_DIR="/var/cache/unified_agent"
	ND="/etc/nginx/ssl"
	NGINX_DEFAULTS="/etc/default/nginx"
	CONFFILE="/etc/nginx/nginx-solomon.conf"

	check_exist -d 755 unified_agent:unified_agent $UNI_DIR
	check_exist -d 700 unified_agent:unified_agent $UNI_CACHE_DIR
	check_exist -d 700 root:root $SSLDIR
	check_exist -d 755 www-data:www-data ${DISCOVERY_DIR}/data
	check_exist -d 755 www-data:www-data ${DISCOVERY_DIR}/www

	check_mod 755 user_gateway:group_solomon /Berkanavt/solomon/gateway

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

	for _app in agent gateway discovery ; do
		if ! /bin/systemctl enable yandex-solomon-${_app} ; then
			echo "Cannot enable ${_app} service!"
		fi
	done
}

case "$1" in
	configure)
		enable
	;;
esac
