#!/bin/sh -e

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

APP="project-manager"
APP_ROOT="${SOLOMON_ROOT}/${APP}"
APP_CONFDIR="${SOLOMON_ROOT}/configs"

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

ENVFILE="/etc/solomon/env"
ND="/etc/nginx"
SE="$ND/sites-enabled"
SA="$ND/sites-available"
CONF="pm.conf"
CONFFILE="$ND/nginx-pm.conf"
NGINX_DEFAULTS="/etc/default/nginx"

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)"
        case $ENV in
            testing|prestable|production|cloud-prod|cloud-preprod)
                ln -sf ${APP_CONFDIR}/${APP}.${ENV}.conf ${APP_CONFDIR}/${APP}.conf
            ;;
            *)
                echo "Cannot determine environment: $ENV"
                exit 1
            ;;
        esac

        # prepare for nginx
        /usr/bin/install -m 700 -o root -g root -d $ND/ssl
        echo "CONFFILE=$CONFFILE" > $NGINX_DEFAULTS
        echo "ulimit -n 16384" >> $NGINX_DEFAULTS

        # set nginx config and reload
        ln -svf $SA/$CONF $SE/$CONF
        if which nginx >/dev/null && nginx -qt -c $CONFFILE ; then
            nginx -s reload -c $CONFFILE
        else
            echo "Ningx configuration failed"
        fi

        # set certs and keys
        for F in pm_cert pm_key ; do
            /usr/local/bin/secrets decrypt \
                --in /Berkanavt/solomon/configs/ssl.${F}.${ENV} \
                --out $ND/ssl/${F}.pem \
                --user root
        done

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

        /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

        TUNUP="/usr/lib/yandex-netconfig/ya-slb-tun"
        if [ -x $TUNUP ] ; then
            $TUNUP restart
        fi
    ;;
esac
