#!/bin/bash
# postinst script for #PACKAGE#
#
# 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 https://www.debian.org/doc/debian-policy/ or
# the debian-policy package


case "$1" in
    configure)


     ### START gather all the info from the box and generate the variabels

        #source /etc/wit-net.conf
 	export DOMAINNAME=${HOSTNAME#*.}
	export LOOPBACKv4=$(dig a +short ${HOSTNAME%%.*}.loopback.${HOSTNAME#*.})
	export LOOPBACKv6=$(dig aaaa +short ${HOSTNAME%%.*}.loopback.${HOSTNAME#*.})
	export TIER_ID=$(echo $LOOPBACKv4 | cut -d . -f 3)
	export NODE_ID=$(echo $LOOPBACKv4 | cut -d . -f 4)

	if [ -z $LOOPBACKv4 ] || [ -z $LOOPBACKv6 ]; then
	    echo "unable to find my LOOPBACK IP: $LOOPBACKv4/$LOOPBACKv6"
	    exit 2
        fi
        if [ -z "$TIER_ID" ] || [ -z "$NODE_ID" ]; then
            echo "Unable to autodetect TIER/NODE_ID: $TIER_ID/$NODE_ID"
            exit 2
        fi
        if [ -z "$DOMAINNAME" ]; then
            echo "Unable to autodetect DOMAINNAME, looks like we deal with a special case, please set in environment and/or update the code"
            exit 2
        fi


        export NODE_ASN="4200$(printf "%03d" $TIER_ID)$(printf "%03d" $NODE_ID)"

        MGMT_MAC=$(ip -br link show dev $(ip -4 -br addr | grep 10.0. | awk '{ print $1 }') | awk '{ print $3 }')

     ## END variables


     ## START writing config files

      # write hosts file
	sed -i -e "/debcore1/d" -e "/${HOSTNAME%%.*}/d" -e "/${LOOPBACKv4}/d" /etc/hosts
	echo -e "${LOOPBACKv4}\t${HOSTNAME}\t${HOSTNAME%%.*}" >>/etc/hosts



      # disable password logins on ssh
        sed -i -e '/#*\s*PasswordAuthentication /d' /etc/ssh/sshd_config
        echo "PasswordAuthentication no" >>/etc/ssh/sshd_config



      # set network interface configurations
        cat <<-EOF >/etc/network/interfaces.d/lo
		auto lo
		iface lo inet loopback

		iface lo inet static
		    address ${LOOPBACKv4}/32
		iface lo inet6 static
		    address ${LOOPBACKv6}/128
	EOF

	cat <<-"EOF" >/etc/network/interfaces.d/mgmt1
		auto mgmt1
		iface mgmt1 inet6 auto
		iface mgmt1 inet dhcp
		    pre-up /bin/ip link add mgmt type vrf table mgmt
		    pre-up /bin/ip link set up dev mgmt
		    pre-up /bin/ip link set master mgmt dev mgmt1
		    post-down /bin/ip link del dev mgmt
	EOF

	cat <<-"EOF" >/etc/network/interfaces.d/feth
	auto feth1
	iface feth1 inet manual
	    mtu 9000

	auto feth2
	iface feth2 inet manual
	    mtu 9000
	EOF




      # set frr config
        sed -i -e "s/FRRROUTERID/${LOOPBACKv4}/" -e "s/NODEASN/${NODE_ASN}/" /etc/frr/frr.conf.wit 
        chown frr.frr /etc/frr/frr.conf.wit /etc/frr/daemons.wit




      # set ipsec config
        sed -i -e "s/HOSTNAME\.DOMAINNAME/${HOSTNAME}/" /etc/ipsec.conf.wit
        echo ": RSA ${HOSTNAME}.key" >/etc/ipsec.secrets




      # write udev rules for device names
        echo 'SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="'$MGMT_MAC'", ATTR{type}=="1", NAME="mgmt1"' >/etc/udev/rules.d/70-persistent-net.rules
        i=0
        for nic in $(ip -br link | awk '{ print $1 }'); do
            if ethtool $nic | grep -q 10000; then
                i=$((i+1))
                echo 'SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="'$(cat /sys/class/net/$nic/address)'", ATTR{type}=="1", NAME="feth'$i'"' >>/etc/udev/rules.d/70-persistent-net.rules
            fi
        done
        sed -i "/$MGMT_MAC.*feth./d" /etc/udev/rules.d/70-persistent-net.rules




      # wite grub rules for serial terminal
	sed -i -e '/GRUB_CMDLINE_LINUX_DEFAULT=/d' -e '/GRUB_CMDLINE_LINUX=/d' -e '/GRUB_SERIAL_COMMAND=/d' -e '/GRUB_TERMINAL=/d' /etc/default/grub
	cat <<-EOF >>/etc/default/grub
		GRUB_CMDLINE_LINUX_DEFAULT=""
		GRUB_CMDLINE_LINUX="console=tty0 console=ttyS1,115200n8"
		GRUB_TERMINAL=serial
		GRUB_SERIAL_COMMAND="serial --speed=115200 --unit=1 --word=8 --parity=no --stop=1"
	EOF


    ## END config file section


    ## START configuring services as we need it

        systemctl enable firewall
        systemctl restart systemd-timesyncd
        systemctl restart ssh
        
        update-grub
        
        sysctl -p /etc/sysctl.d/10-frr.conf

    ## END services section


    ;;

    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