#!/bin/sh -e

SOLOMON_ROOT="/Berkanavt/solomon"

APP="dataproxy"
APP_ROOT="${SOLOMON_ROOT}/${APP}"
APP_CONFDIR="${SOLOMON_ROOT}/configs"

USER="user_${APP}"
GROUP="group_solomon"
LOGS_DIR="/logs"
COREDUMPS_DIR="/coredumps/${APP}"

case "$1" in
    configure)
        if [ ! -e ${LOGS_DIR} ]; then
            /usr/bin/install -g ${GROUP} -m 775 -d ${LOGS_DIR}
        fi
        if [ ! -e ${COREDUMPS_DIR} ]; then
            /usr/bin/install -g ${GROUP} -o ${USER} -m 755 -d ${COREDUMPS_DIR}
        fi

        /bin/chown ${USER}:${GROUP} ${APP_ROOT}

        ENV="$(cat /etc/solomon/env)"
        case ${ENV} in
            # prestable)
            #     # special hack to start DataProxy without STS support
            #     ln -sf ${APP_CONFDIR}/${APP}.${ENV}.without-sts.conf ${APP_CONFDIR}/${APP}.conf
            #     ;;
            testing|prestable|production|cloud-*)
                ln -sf ${APP_CONFDIR}/${APP}.${ENV}.conf ${APP_CONFDIR}/${APP}.conf
                ;;
            *)
                echo "Cannot determine environment: $ENV"
                exit 1
                ;;
        esac

        if [ -x /bin/systemctl -a -f /etc/systemd/system/yandex-solomon-${APP}.service ] ; then
            /bin/systemctl stop yandex-solomon-${APP} || true
            /bin/systemctl daemon-reload

            if ! /bin/systemctl enable yandex-solomon-${APP} ; then
                echo "Cannot enable ${APP} service!"
            fi
            if ! /bin/systemctl restart yandex-solomon-${APP} ; then
                echo "Cannot restart ${APP} service!"
            fi
        elif [ -x /usr/bin/service -a -f /etc/init/yandex-solomon-${APP}.conf ] ; then
            if ! /usr/bin/service yandex-solomon-${APP} restart ; then
                echo "Cannot restart ${APP} service!"
            fi
        fi
        ;;
    *)
        ;;
esac
