#!/bin/bash
# postinst script 
#
# 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

configure_settings()
{
    # we do not allow users crontab, so disable it with empty cron.allow
    echo -n "" > /etc/cron.allow

    # disable fstrim-all
    test -f /etc/cron.weekly/fstrim && sed -i "s/^exec fstrim-all/\#exec fstrim-all/" /etc/cron.weekly/fstrim

    # enable mellanox ethernet driver
    grep -q "mlx4_en" /etc/modules || echo "mlx4_en" >> /etc/modules

    # setup host-specific configs
    _my_fqdn=$(uname -n)
    _my_postfix_cf="/etc/postfix/main.cf"
    _my_root_mail="disk-root@yandex-team.ru"

    #postfix
    if [ -n "${_my_fqdn}" ] ; then
        echo "${_my_fqdn}" > /etc/mailname
        sed -i "s/%%HOSTNAME%%/${_my_fqdn}/g" ${_my_postfix_cf}
        sed -i "s/myhostname =.*/myhostname = ${_my_fqdn}/g" ${_my_postfix_cf}
        sed -i "s/mydestination =.*/mydestination = ${_my_fqdn}, localhost/g" ${_my_postfix_cf}
    fi

    if grep -q "relayhost.*=" ${_my_postfix_cf} ; then
        sed -i "s/relayhost.*=.*/relayhost = outbound-relay.yandex.net/" ${_my_postfix_cf}
    else
        echo "relayhost = outbound-relay.yandex.net" >> ${_my_postfix_cf}
    fi

    grep -q "^root.*:.*yandex.*" /etc/aliases || \
        ( echo "root: ${_my_root_mail}" >> /etc/aliases ; newaliases )


    # enable autofix filesystems if unclean mount was detected
    grep -q "^FSCKFIX.*=.*yes" /etc/default/rcS || \
        (sed -i -r -e "/.*FSCKFIX.*/d" /etc/default/rcS ;echo "FSCKFIX=yes" >> /etc/default/rcS)


    # tune grub
    sed -i -r -e "/.*GRUB_HIDDEN_TIMEOUT.*/d" /etc/default/grub

    sed -i -r -e "s/ quiet//" /etc/default/grub

    grep -q "^GRUB_TIMEOUT=5" /etc/default/grub || \
        (sed -i -r -e "/.*GRUB_TIMEOUT.*=/d" /etc/default/grub ; echo "GRUB_TIMEOUT=5" >> /etc/default/grub)

    grep -q "^GRUB_TERMINAL=console" /etc/default/grub || \
        (sed -i -r -e "/.*GRUB_TERMINAL.*=/d" /etc/default/grub ; echo "GRUB_TERMINAL=console" >> /etc/default/grub)

    grep -q "^GRUB_RECORDFAIL_TIMEOUT=2" /etc/default/grub || \
        (sed -i -r -e "/.*GRUB_RECORDFAIL_TIMEOUT.*=/d" /etc/default/grub ;  echo "GRUB_RECORDFAIL_TIMEOUT=2" >> /etc/default/grub)

    grep -q "GRUB_CMDLINE_LINUX_DEFAULT=.*consoleblank=0" /etc/default/grub || \
        sed -i -r -e "s/GRUB_CMDLINE_LINUX_DEFAULT=\"/GRUB_CMDLINE_LINUX_DEFAULT=\"consoleblank=0 /" /etc/default/grub


    # tune mdadm
    if [ -f /etc/initramfs-tools/conf.d/mdadm ] ; then 
        grep -q "^BOOT_DEGRADED=true" /etc/initramfs-tools/conf.d/mdadm || \
            sed -i -r -e "s/.*BOOT_DEGRADED=.*/BOOT_DEGRADED=true/" /etc/initramfs-tools/conf.d/mdadm
    else
        echo "BOOT_DEGRADED=true" > /etc/initramfs-tools/conf.d/mdadm
    fi

    grep -q "^AUTOCHECK=false" /etc/default/mdadm || \
        sed -i -r -e "s/.*AUTOCHECK.*=.*/AUTOCHECK=false/" /etc/default/mdadm ; 

    grep -q "^MAILADDR.*yandex.*" /etc/mdadm/mdadm.conf || \
        sed -i "s/^MAILADDR.*/MAILADDR ${_my_root_mail}/g" /etc/mdadm/mdadm.conf


    # configure locales
    for locale in en_US.UTF-8 ru_RU.UTF-8 ; do
        locale-gen $locale >/dev/null
    done
    dpkg-reconfigure -f noninteractive locales >/dev/null && update-locale


    # configure timezone
    echo "Europe/Moscow" > /etc/timezone
    [ -s /usr/share/zoneinfo/Europe/Moscow ] && cp -f /usr/share/zoneinfo/Europe/Moscow /etc/localtime
    dpkg-reconfigure -f noninteractive tzdata


    # tune fsck interval
    for DEVICE in $(awk '$3 ~ /ext[2-4]/ {print $1}' /etc/fstab); do
        if [ x"${DEVICE##UUID=}" != x"${DEVICE}" ]; then
            DEVICE=$(blkid -t $DEVICE | awk -F':' '{print $1}')
        fi
        echo "Running 'tune2fs -i0 -c0 $DEVICE'"
        tune2fs -i0 -c0 $DEVICE >/dev/null
    done

    # tune ssh_config
    sed -i -e "s/.* ForwardAgent .*/    ForwardAgent yes/" /etc/ssh/ssh_config
    sed -i -e "s/.* RhostsRSAAuthentication .*/    RhostsRSAAuthentication yes/" /etc/ssh/ssh_config
    sed -i -e "s/.* RSAAuthentication .*/    RSAAuthentication no/" /etc/ssh/ssh_config
    sed -i -e "s/.* StrictHostKeyChecking .*/    StrictHostKeyChecking no/" /etc/ssh/ssh_config

    # configure alternatives
    _update_alternatives=$(which update-alternatives)
    if [ -x "${_update_alternatives}" ]; then
        ${_update_alternatives} --install /bin/sh sh /bin/bash 100
        ${_update_alternatives} --install /usr/bin/editor editor /usr/bin/vim 100
    fi

}


configure_modules()
{
    local _disk_modules="tunnel4 tunnel6 ip_tables ip6_tables ip_tunnel ip6_tunnel nf_conntrack_ipv4 nf_conntrack_ipv6"
    for module in $_disk_modules
    do
        grep -q $module /etc/modules || \
        echo $module >> /etc/modules && modprobe $module
    done
}

configure_properties()
{
    # get-machine-properties generates different files according to output file extension
    # that's why there is two different executions
    get-machine-properties -O /etc/yandex/machine.properties
    get-machine-properties -O /etc/yandex/machine.conf
}

configure_selfdns() {
    # Replace selfdns default.conf by disk.conf, if exists
    # ex.: yasetup -p /etc/yandex/selfdns-client/disk.conf,~/selfdns-client.disk.conf,0644,root:root ...
    if [ -f /etc/yandex/selfdns-client/disk.conf ]; then
        ln -sf /etc/yandex/selfdns-client/disk.conf /etc/yandex/selfdns-client/default.conf
    fi
}

case "$1" in
    configure)
        configure_settings || true
        configure_properties || true
        ( chown root:root /etc/cron.hourly/ntpdate ; chmod 755 /etc/cron.hourly/ntpdate ) || true
        ( chown root:root /etc/cron.d/get-machine-properties ; chmod 755 /etc/cron.d/get-machine-properties ) || true
        sysv-rc-conf ondemand off || true
        sysv-rc-conf ipmievd off || true
        sysv-rc-conf openipmi off || true
        service ssh restart || true
        service postfix restart || true
        service cron restart || true
        update-initramfs -u || true
        update-grub || true
        configure_modules || true
        configure_selfdns || true
    ;;

    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
