#!/bin/sh
# postinst script for test-0.1
#
# see: dh_installdeb(1)

set -e

# summary of how this script can be called:
#        * <postinst> `configure' <most-recently-configured-version>
#        * <old-postinst> `abort-upgrade' <new version>
#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
#          <new-version>
#        * <postinst> `abort-remove'
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <version> `removing'
#          <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package

case "$1" in
configure)

    yav-deploy --force --skip-post-update \
        -c /etc/yandex/yav-deploy/pkg/yandex-passport-yasms-internal/ ||
        true

    CURRENT_ENV_TYPE=$(cat "/etc/yandex/environment.type")
    CURRENT_ENV_NAME=""
    if [ -f /etc/yandex/environment.name ]; then
        CURRENT_ENV_NAME=`cat "/etc/yandex/environment.name"`
    fi
    CURRENT_HOSTNAME=$(hostname -s)

    ## common
    chown -R www-data: /etc/yandex/passport-yasms-internal
    chown -R www-data: /var/log/yandex/passport-yasms-internal

    ## cfg
    echo "Generating config."
    python3 /etc/yandex/passport-yasms-internal/prepare.py \
        "/etc/yandex/passport-yasms-internal/template.json" \
        "$CURRENT_ENV_TYPE" \
        "$CURRENT_ENV_NAME" \
        "$CURRENT_HOSTNAME" >/etc/yandex/passport-yasms-internal/yasms_internal.conf

    ## yasm
    echo "Restarting yasmagent."
    YENV_PROJECT="passport.yasms_internal" /usr/share/passport-admin-config-golovan/passport_golovan_config.py \
        --itype="passportyasms_internal" > \
        /etc/yandex/yasmagent/instances.d/passport.yasms_internal.instance
    YENV_PROJECT="passport.yasms_internal" /usr/share/passport-admin-config-golovan/passport_golovan_config.py \
        --itype="common" >> \
        /etc/yandex/yasmagent/instances.d/passport.yasms_internal.instance
    invoke-rc.d yasmagent restart || /bin/true

    ## monrun
    echo "Restarting monrun."
    regenerate-monrun-tasks
    service juggler-client restart

    ## yasms_internal
    echo "Updating sysmtemctl."
    if ! systemctl is-enabled yandex-passport-yasms-internal >/dev/null; then
        systemctl enable yandex-passport-yasms-internal || true
    fi
    systemctl --system daemon-reload || true

    echo "Trying to check logstoreagent configs..."
    sudo -u www-data /usr/sbin/logstoreagent_config_checker
    echo "Trying to check logstoreagent configs...OK"

    systemctl restart yandex-passport-logstoreagent
    systemctl restart yandex-passport-yasms-internal

    ;;

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

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

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
