#!/bin/bash

BASE=/opt/www/passport

set -e

case "$1" in
    configure)
        chmod 775 $BASE

        find $BASE \
            -mindepth 0 -maxdepth 1 \
            -type d \
            -exec chmod g+s {} \; \
            -exec chgrp passpadmin -R {} \;

        mkdir -p $BASE/log
        mkdir -p $BASE/log/arc
        mkdir -p $BASE/log/parse

        find $BASE/log \
            ! -name 'push-client*' \
            -exec chown www-data {} \;

        mkdir -p -m777 /opt/tmp
        mkdir -p -m775 /opt/tmp/admin-background-tasks
        chown www-data:www-data /opt/tmp/admin-background-tasks

        $BASE/conf/configurator --hosts $BASE/admin/etc/hosts --input $BASE/admin/apache/httpd-adm.conf --output /usr/local/apache/conf/httpd-adm.conf

        cp --preserve=mode $BASE/admin/apache/apache-adm             /etc/init.d/
        cp --preserve=mode $BASE/admin/apache/apache-adm-restart     /etc/init.d/

        $BASE/conf/configurator --hosts $BASE/admin/etc/hosts --input $BASE/admin/nginx/admyandexnet.conf --output /etc/nginx/sites-available/admyandexnet.conf
        ln -fs /etc/nginx/sites-available/admyandexnet.conf /etc/nginx/sites-enabled/admyandexnet.conf

        $BASE/conf/configurator --hosts $BASE/admin/etc/hosts --input $BASE/admin/etc/passport.conf.tt --output $BASE/admin/etc/conf/passport.conf
        $BASE/conf/configurator --hosts $BASE/admin/etc/hosts --input $BASE/admin/etc/access.conf.tt   --output $BASE/admin/etc/conf/access.conf
        $BASE/conf/detector     --hosts $BASE/admin/etc/hosts --short-key > $BASE/admin/data/hna

        /etc/init.d/apache-adm-restart

        [ -e /etc/init.d/nginx ] && ( [ -f /var/run/nginx.pid ] && /etc/init.d/nginx reload || /etc/init.d/nginx restart ) || :
    ;;

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

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