#!/bin/sh
# postinst script for yandex-social-nginx
#
# 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

BASE=/opt/www/social
ENVTYPE=`cat /etc/yandex/environment.type`
ENVNAME=`[ -e /etc/yandex/environment.name ] && cat /etc/yandex/environment.name || echo undef`
HOSTIP=`host $(hostname -f) | sed -e 's/^.* has \(IPv6 \)\?address //' | head -1`

setup_temp_dirs() {
    mkdir -p -m700 /opt/tmp/client_body_temp
    mkdir -p -m700 /opt/tmp/proxy_temp
    mkdir -p -m700 /opt/tmp/fastcgi_temp

    chown www-data:www-data /opt/tmp/client_body_temp
    chown www-data:www-data /opt/tmp/proxy_temp
    chown www-data:www-data /opt/tmp/fastcgi_temp

    chmod 777 /opt/tmp
}

setup_log_dirs() {
    mkdir -p $BASE/log
    chown www-data:www-data $BASE/log
}

generate_confs() {
    template_to_conf nginx.conf > /etc/nginx/nginx.conf

    template_to_conf sites-ru.conf > /etc/nginx/sites-available/ru.conf
    ln -fs /etc/nginx/sites-available/ru.conf  /etc/nginx/sites-enabled/ru.conf

    template_to_conf sites-net.conf > /etc/nginx/sites-available/net.conf
    ln -fs /etc/nginx/sites-available/net.conf /etc/nginx/sites-enabled/net.conf

    if [ "$ENVTYPE" != "development" ];
    then
        template_to_conf sites-api.conf > /etc/nginx/sites-available/api.conf
        ln -fs /etc/nginx/sites-available/api.conf /etc/nginx/sites-enabled/api.conf
    else
        template_to_conf multiport-dev.conf > /etc/nginx/sites-available/multiport.conf
        ln -fs /etc/nginx/sites-available/multiport.conf /etc/nginx/sites-enabled/multiport.conf
    fi
}

template_to_conf() {
    $BASE/script/nginx-conf-generate --envtype $ENVTYPE --envname $ENVNAME \
                                               --hostip $HOSTIP --input "$1"
}

restart_nginx() {
    [ -e /etc/init.d/nginx ] && (
        [ -f /var/run/nginx.pid ] && /etc/init.d/nginx reload || /etc/init.d/nginx restart
    ) || true
}

case "$1" in
    configure)
        setup_temp_dirs
        setup_log_dirs
        generate_confs
        restart_nginx
    ;;

    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
