#!/bin/bash
#
# postinst script for linuxmuster-base
# thomas@linuxmuster.net
# 20201126
# GPL v3
#

# 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>
#        * <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
#

# get constants
source /usr/share/linuxmuster/defaults.sh
datestr="$(date +%Y%m%d%H%M)"

case "$1" in

 configure)

  # add lmn paths to python environment
  usersite="$(python3 -c 'import site; site._script()' --user-site)"
  userpth="$usersite/lmn.pth"
  mkdir -p "$usersite"
  echo "$LIBDIR" > "$userpth"
  echo "$SETUPDIR" >> "$userpth"

  # clean and bytecompile modules
  find "$LIBDIR" -name \*.pyc -exec rm '{}' \;
  find "$LIBDIR" -type d -name __pycache__ -exec rm -r '{}' \; 2> /dev/null || true
  python3 -m compileall "$LIBDIR"

  # create ssl-cert group
  groupadd --force --system ssl-cert

  # permissions
  chgrp ssl-cert "$SSLDIR" -R
  chmod 750 "$SSLDIR"
  for i in "$SECRETDIR" "$BINDUSERSECRET" "$DNSADMINSECRET"; do
    [ -e "$i" ] && chgrp dhcpd "$i"
    if [ -d "$i" ]; then
      chmod 750 "$i"
    else
      [ -e "$i" ] && chmod 440 "$i"
    fi
  done
  sysvol="/var/lib/samba/sysvol"
  [ -d "$sysvol" ] && find "$sysvol" -type d -exec chmod 775 '{}' \;

  # skip subsequent actions on configured systems
  [ -s "$SETUPINI" ] || exit 0

  # create firewall fullchain pem file
  fwcert="$(echo "$FWFULLCHAIN" | sed -e 's|.fullchain.|.cert.|')"
  if [ ! -s "$FWFULLCHAIN" -a -s "$fwcert" ]; then
    echo "Creating $(basename "$FWFULLCHAIN")."
    cat "$fwcert" "$CACERT" > "$FWFULLCHAIN"
    chmod 640 "$FWFULLCHAIN"
  fi

  # provide cacert.pem for clients if not present
  if [ -n "$domainname" -a -s "$CACERT" ]; then
    sysvoltlsdir="$(echo "$SYSVOLTLSDIR" | sed -e 's|@@domainname@@|'"$domainname"'|')"
    sysvolpemfile="$sysvoltlsdir/$(basename "$CACERT")"
    [ -d "$sysvoltlsdir" ] || mkdir -p "$sysvoltlsdir"
    if [ -d "$sysvoltlsdir" -a ! -e "$sysvolpemfile" ]; then
      echo "Providing $sysvolpemfile."
      cp "$CACERT" "$sysvolpemfile"
    fi
  fi

  # timesyncd update, add firewall ip as parent ntp server
  conf='/etc/systemd/timesyncd.conf'
  if [ -e "$conf" ]; then
    search="NTP=${firewallip}"
    if ! grep -q ^"$search" "$conf"; then
      echo "Updating time server related timesyncd configuration."
      cp "$conf" "$conf".dpkg-bak."$datestr"
      echo "$search" >> "$conf"
      systemctl daemon-reload
    fi
  fi

  # smb.conf update (pr #105), deprecated
  #conf="/etc/samba/smb.conf"
  #search="# 20200818"
  #if ! grep -q ^"$search" "$conf"; then
  #  echo "Updating samba configuration."
  #  cp "$conf" "$conf".dpkg-bak."$datestr"
  #  tpl="$TPLDIR/smb.conf"
  #  sed -e "s|@@sambadomain@@|$sambadomain|g
  #          s|@@realm@@|$realm|g
  #          s|@@firewallip@@|$firewallip|g
  #          s|@@netbiosname@@|$netbiosname|g
  #          s|@@servername@@|$servername|g
  #          s|@@domainname@@|$domainname|g" "$tpl" > "$conf"
  #  systemctl reload samba-ad-dc.service
  #fi
  # check ntp ntpsigndsocket
  #ntpsigndsocket="/run/samba/ntp_signd"
  #if [ ! -d "$ntpsigndsocket" ]; then
  #  mkdir -p "$ntpsigndsocket"
  #  systemctl restart samba-ad-dc.service
  #  sleep 2
  #fi
  #chgrp ntp "$ntpsigndsocket"

  # create dns-admin account
  if ! id dns-admin &> /dev/null; then
    echo "Creating dns-admin account."
    # create user password
    conf="$DNSADMINSECRET"
    dnspw="$(python3 -c 'from functions import randomPassword; print(randomPassword(16))')"
    echo "$dnspw" > "$conf"
    chgrp dhcpd "$conf"
    chmod 440 "$conf"
    # create account
    desc="Unprivileged user for DNS updates via DHCP server"
    auth="-U administrator --password="$(cat "$ADADMINSECRET")""
    samba-tool user create dns-admin "$dnspw" --description="$desc" $auth
    samba-tool user setexpiry dns-admin --noexpiry $auth
    samba-tool group addmembers DnsAdmins dns-admin $auth
  fi

  # dhcpd updates
  conf='/etc/dhcp/events.conf'
  if [ ! -e "$conf" ] || ! grep -q '# 20200418' "$conf" ; then
    echo "Updating dhcp configuration."
    cp "$TPLDIR/dhcpd.events.conf" "$conf"
    conf='/etc/dhcp/dhcpd.conf'
    cp "$conf" "$conf".dpkg-bak."$datestr"
    tpl="$TPLDIR/dhcpd.conf"
    sed -e "s|@@servername@@|$servername|g
            s|@@domainname@@|$domainname|g
            s|@@serverip@@|$serverip|g" "$tpl" > "$conf"
    systemctl restart isc-dhcp-server.service
  fi
  # apparmor dhcp update
  conf="/etc/apparmor.d/local/usr.sbin.dhcpd"
  if ! grep -q dhcpd-update-samba-dns.py "$conf"; then
    echo "Updating apparmor configuration."
    cp "$conf" "$conf".dpkg-bak."$datestr"
    cp "$TPLDIR/dhcpd.apparmor.d" "$conf"
    systemctl restart apparmor.service
  fi

  # enable ntp service, change firewall name to ip (#88)
  if timedatectl status | grep -qi 'active: yes'; then
    echo "Disabling timesyncd service."
    timedatectl set-ntp false
  fi
  if systemctl status ntp | grep -qi 'inactive (dead)'; then
    echo "Enabling & starting ntp service."
    systemctl enable ntp.service
    systemctl start ntp.service
  fi
  # deprecated
  #conf="/etc/ntp.conf"
  #search="# 20200818"
  #if ! grep -q ^"$search" "$conf"; then
  #  echo "Updating ntp configuration."
  #  cp "$conf" "$conf".dpkg-bak."$datestr"
  #  tpl="$TPLDIR/ntp.conf"
  #  sed -e "s|@@firewallip@@|$firewallip|g" "$tpl" > "$conf"
  #  cp "$tpl.admin" "$conf.admin"
  #  cp "$tpl.dist" "$conf.dist"
  #  systemctl restart ntp.service
  #fi

  # remove obsolete sudo users for webui (#90)
  for i in student teacher; do
    id "$i" &> /dev/null && userdel "$i"
    [ -e "/etc/sudoers.d/$i" ] && rm "/etc/sudoers.d/$i"
  done

  # install necessary sudoers config for webui (#91)
  tpl="$TPLDIR/webui-sudoers"
  conf="$(head -1 $tpl | awk '{ print $2 }')"
  search="# 20200720"
  if [ ! -e "$conf" ] || ! grep -q ^"$search" "$conf"; then
    echo "Updating webui sudoers."
    sed -e "s|@@sambadomain@@|$sambadomain|g" "$tpl" > "$conf"
    chmod 400 "$conf"
  fi

  # fix #83, patch opnsense's web-proxy sso configuration (only if system is configured)
  if [ -e "$FWAPIKEYS" ]; then
    # test ssh link to firewall
    if ssh -q -oBatchMode=yes -oStrictHostKeyChecking=accept-new "$firewallip" exit; then
      echo "SSH connection to firewall $firewallip successfully established."
    else
      echo "SSH connection to firewall $firewallip failed!"
      exit 0
    fi
    # remove obsolete configs
    squiddir="/usr/local/etc/squid"
    confs="$squiddir/auth/credentialsttl.conf $squiddir/pre-auth/50-linuxmuster.auth.conf"
    for conf in $confs; do
      if ssh -q -oBatchMode=yes -oStrictHostKeyChecking=accept-new "$firewallip" ls "$conf" &> /dev/null; then
        echo "Removing obsolete opnsense configfile $(basename $conf)."
        ssh "$firewallip" rm -f "$conf"
        restart="yes"
      fi
    done
    # create new config file
    conf="$(head -1 $FWAUTHCFG | awk '{ print $2 }')"
    if ! ssh -q -oBatchMode=yes -oStrictHostKeyChecking=accept-new "$firewallip" ls "$conf" &> /dev/null; then
      echo "Creating new opnsense configfile $(basename $conf)."
      # create config file
      "$FWSHAREDIR/create-auth-config.py"
      conftmp="/tmp/$(basename $FWAUTHCFG)"
      [ -s "$conftmp" ] || exit 0
      scp "$conftmp" "$firewallip":"$conf"
      rm -f "$conftmp"
      restart="yes"
    fi
    if [ -n "$restart" ]; then
      echo "Restarting proxy:"
      ssh "$firewallip" pluginctl -s squid restart
    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
