#!/bin/sh


set -e


#-------------------------------------------------------------------------


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


#-------------------------------------------------------------------------


post_install() {
    APP="yandex-solomon-discovery"
    BASE_DIR="/Berkanavt/solomon/discovery"
    CONF_DIR="${BASE_DIR}/config"
    ENV_FILE="/etc/solomon/env"

    if [ -r "$ENV_FILE" ] ; then
        ENV="$(cat $ENV_FILE)"
        echo "Got $ENV environment"
    else
        echo "Cannot read environment file $ENV_FILE"
        exit 1
    fi
    case $ENV in
        testing)
            ;;
        prestable|production)
            for DC in man myt sas vla ; do
                /usr/local/bin/secrets decrypt \
                    --in ${CONF_DIR}/k8s_${DC}.secret.${ENV} \
                    --out ${CONF_DIR}/k8s_${DC}.conf \
                    --user www-data
            done
            ;;
        cloud-preprod|cloud-prod)
            ;;
        *)
            echo "Cannot determine environment: $ENV"
    esac
    ln -vsf discovery.conf.${ENV} ${CONF_DIR}/discovery.conf

    for D in ${BASE_DIR}/data ${BASE_DIR}/www ; do
        check_exist -d 755 www-data:www-data $D
    done

    /bin/systemctl daemon-reload
    if [ -x /bin/systemctl -a -f /etc/systemd/system/${APP}.service ] ; then
        if ! /bin/systemctl enable ${APP} ; then
            echo "Cannot enable ${APP} service!"
        fi
        if ! /bin/systemctl restart ${APP} ; then
            echo "Cannot restart ${APP} service!"
        fi
    fi
}


#-------------------------------------------------------------------------


case "$1" in
    configure)
        post_install
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

    *)
        echo "postinst was called with unknown argument '$1'" >&2
        exit 1
    ;;
esac

#DEBHELPER#

exit 0
