#!/bin/sh -e

SOLOMON_ROOT="/Berkanavt/solomon"
SECRETS_ROOT="${SOLOMON_ROOT}/secrets"

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

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

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

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

        ENV="$(cat /etc/solomon/env)"
        DC="$(cat /etc/solomon/dc)"
        CLUSTER="$(cat /etc/solomon/cluster 2>/dev/null || true)"
        CONF=${APP_CONFDIR}/${APP}.conf

        case $ENV in
            testing|prestable|production|cloud-*)
                if [ -f "${APP_CONFDIR}/${APP}.${ENV}.${DC}.conf" -a -z "$CLUSTER" ]; then
                    ln -vsf ${APP_CONFDIR}/${APP}.${ENV}.${DC}.conf $CONF
                else
                    sed "s/{{CLUSTER}}/${CLUSTER}/g; s/{{DC}}/${DC}/g; s/{{ENV}}/${ENV}/g;" \
                        ${APP_CONFDIR}/${APP}.${ENV}.conf > ${CONF}.tmp
                    mv -vf ${CONF}.tmp ${CONF}
                fi
                ;;
            *)
                echo "Cannot determine environment: $ENV"
                exit 1
                ;;
        esac

        /usr/local/bin/secrets decrypt \
            --in ${APP_CONFDIR}/${APP}.${ENV}.secrets \
            --out ${SECRETS_ROOT}/${APP}.secrets \
            --user ${USER}

        if [ -x /bin/systemctl -a -f /etc/systemd/system/yandex-solomon-${APP}.service ] ; then
            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
