#!/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

unprotect_file="chattr -i"

# function searches parameters/values and edits/puts it
update_config_parameter()
{
    local _config_file _config_parameter _config_value _grep_ret

    if [ "$#" -lt 3 ] ; then
        p_err "wrong update_config_parameter function usage"
    fi

    _config_file="$1"
    _config_parameter="$2"
    _config_value="$3"


    # Try to find parameter with needed value
    grep -q "^${_config_parameter} ${_config_value}" ${_config_file} 2>/dev/null
    _grep_ret="$?"

    # if grep exited with 0, parameter already has right value, return 0
    # if grep exited with 1, parameter missing or has wrong value, fix it
    # if grep exited with 2 or even more, something went really wrong, exit immediately
    if [ ${_grep_ret} -eq 0 ] ; then
        return 0

    elif [ ${_grep_ret} -eq 1 ] ; then
        # in case ${_config_file} was protected by chattr/chflags
        ${unprotect_file} ${_config_file}

        sed -i -e "/^${_config_parameter} /d" ${_config_file} || \
            p_err "error editing ${sshd_config_file}"
        echo "${_config_parameter} ${_config_value}" >> ${_config_file} || \
            p_err "error editing ${sshd_config_file}"
    else
        p_err "error parsing ${sshd_config_file}"

    fi

    return 0
}

apply_settings()
{
    # ported from patch-cauth-sshd
    update_config_parameter /etc/ssh/sshd_config LogLevel VERBOSE
    update_config_parameter /etc/ssh/sshd_config PasswordAuthentication no
    update_config_parameter /etc/ssh/sshd_config PermitRootLogin without-password
    # enabling ssh keys resolving (can not use Includes till https://www.openssh.com/txt/release-8.2)
    update_config_parameter /etc/ssh/sshd_config AuthorizedKeysCommand '/usr/bin/curl -s -X GET --unix-socket /run/yandex-cauth-userd.sock http://localhost/nss/v1/keys/%u'
    # run AuthorizedKeysCommand with sshd user to avoid privilege escalation via untrusted code could be running with nobody credentials
    update_config_parameter /etc/ssh/sshd_config AuthorizedKeysCommandUser sshd
    update_config_parameter /etc/ssh/sshd_config RevokedKeys /var/cache/yandex-cauth-userd/krl

    # patching /etc/nsswitch.conf
    [ ! -f /etc/nsswitch.conf.userd-backup ] && cp -f /etc/nsswitch.conf /etc/nsswitch.conf.userd-backup
    if grep -q "^passwd:.*sss.*" /etc/nsswitch.conf
    then
        sed -i -e "s/^\(passwd:.*\)sss\(.*\)/\1 cauth_userd\2/" /etc/nsswitch.conf
        sed -i -e "s/^\(group:.*\)sss\(.*\)/\1 cauth_userd\2/" /etc/nsswitch.conf
    else
        grep "^passwd:.*cauth_userd.*" /etc/nsswitch.conf >/dev/null || \
            sed -i -e "s/^\(passwd:.*\)/\1 cauth_userd/" /etc/nsswitch.conf
        grep "^group:.*cauth_userd.*" /etc/nsswitch.conf >/dev/null || \
            sed -i -e "s/^\(group:.*\)/\1 cauth_userd/" /etc/nsswitch.conf
    fi

    if grep -q "^shadow:.*sss.*" /etc/nsswitch.conf
    then
        sed -i -e "s/^\(shadow:.*\) sss\(.*\)/\1\2/" /etc/nsswitch.conf
    fi
    
    if grep -q "^services:.*sss.*" /etc/nsswitch.conf
    then
        sed -i -e "s/^\(services:.*\) sss\(.*\)/\1\2/" /etc/nsswitch.conf
    fi

    if grep -q "^automount:.*sss.*" /etc/nsswitch.conf
    then
        sed -i -e "s/^\(\)automount:.*sss.*/\1/" /etc/nsswitch.conf
    fi
    if grep -q "^initgroups:.*sss.*" /etc/nsswitch.conf
    then
	sed -i -e "s/^\(initgroups:.*\)sss\(.*\)/\1 cauth_userd\2/" /etc/nsswitch.conf
    else
	grep "^initgroups:.*cauth_userd.*" /etc/nsswitch.conf >/dev/null || \
            sed -i -e "s/^\(initgroups:.*\)/\1 cauth_userd/" /etc/nsswitch.conf
    fi


    # apply configs to /etc/pam.d/common-*
    pam-auth-update --package cauth --force
}



case "$1" in
    configure)
        apply_settings

	# fix permissions
        chmod 0755 /etc/cauth
        chmod 0644 /etc/ldap/certs/cafile.pem
        chmod 0600 /etc/security/yandex-access.conf

        # making /sbin/nologin symlink to allow nologin shell works properly CAUTH-1194
        if [ ! -e /sbin/nologin ]; then
            ln -sf $(which nologin) /sbin/nologin || true
        fi

        # In case this system is running systemd, we need to ensure that all
        # necessary tmpfiles (if any) are created before starting.
        if [ -f /proc/1/exe ] && readlink /proc/1/exe | grep -q systemd
        then
            # reload systemd units
            systemctl daemon-reload

            if [ -z $HOSTMAN ]
            then
                systemctl enable yandex-cauth-userd.service
                systemctl enable yandex-cauth-userd.socket
                systemctl start yandex-cauth-userd.socket
            fi

            # restart/reload services that using nss
            systemctl restart dbus
            # dbus must settle after restart, so add tiny delay before logind restart
            if [ "$(systemctl show systemd-logind -p UnitFilePreset | cut -d= -f2)" = "enabled" ]
            then
                sleep 1s
                systemctl stop systemd-logind
                systemctl daemon-reexec
                systemctl start systemd-logind
            fi
            systemctl reload ssh

            # unfortunately cqudp uses nsswitch.conf and requires restart to use new nss module
            for i in $(pgrep cqudp)
            do
                # restart only dom0 cqudp instance
                grep -q 'pids:/$' /proc/$i/cgroup && kill -9 $i
            done

            # do a bit harmful portod reload (causes porto requests failure for a short period)
            if [ ! -z "$(pgrep portod)" ]
            then
                portod reload
            fi
        fi

    ;;

    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
