#!/bin/sh -e

GRAPHITE_ROOT="/Berkanavt/mega-graphite"

APP="storage"
APP_ROOT="${GRAPHITE_ROOT}/${APP}"
APP_CONFDIR="${GRAPHITE_ROOT}/configs"

USER="user_mgstorage"
GROUP="group_solomon"
LOGS_DIR="/Berkanavt/mega-graphite/logs"


get_instance() {
    name="$(hostname | sed -E 's/^(mega-)?graphite(-([a-z]+))?-([a-z]+)-[0-9]{2}\..*$/\3/')"
    if [ -z "${name}" ]; then
        echo "bs"
    else
        echo "${name}"
    fi
}

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

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

        ENV=$(cat /etc/solomon/env)
        DC=$(cat /etc/solomon/dc)

        case $ENV in
            testing|prestable)
                ln -sf ${APP_CONFDIR}/${APP}.${ENV}.conf ${APP_CONFDIR}/${APP}.conf
                ;;
            production)
                INSTANCE="$(get_instance)"
                ln -sf ${APP_CONFDIR}/${APP}.${ENV}.${INSTANCE}.${DC}.conf ${APP_CONFDIR}/${APP}.conf
                ;;
            *)
                echo "Cannot determine environment: $ENV"
                exit 1
                ;;
        esac

        SVC="mega-graphite-${APP}"
        if [ -x /bin/systemctl -a -f /etc/systemd/system/${SVC}.service ] ; then
            /bin/systemctl daemon-reload
            if ! /bin/systemctl enable ${SVC} ; then
                echo "Cannot enable ${SVC} service!"
            fi
            if ! /bin/systemctl restart ${SVC} ; then
                echo "Cannot restart ${SVC} service!"
            fi
        elif [ -x /usr/sbin/service -a -f /etc/init/${SVC}.conf ] ; then
            initctl reload-configuration
            sleep 1
            if ! /usr/sbin/service ${SVC} restart ; then
                echo "Cannot restart ${SVC} service!"
            fi
        fi
        ;;
    *)
        ;;
esac
