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

package=linuxmuster-freeradius
now=`date`
tpldir=/var/lib/linuxmuster/config-dynamic/55_freeradius
tagstr="## This configuration file was automatically created by linuxmuster"

case "$1" in

 configure)

  # read linuxmuster defaults
  . /usr/share/linuxmuster/config/dist.conf
  . $HELPERFUNCTIONS

  # check if freeradius is already configured
  if [ ! -d /etc/freeradius ]; then
   echo "freeradius configuration not found! Aborting!"
   exit 0
  fi

  # necessary secrets
  radiussecret=`pwgen 8 1 scn`
  ldappassword=`cat /etc/ldap.secret`

  # patch configuration if it was not done yet
  for i in $tpldir/*.target; do

   targetcfg=`cat $i`
   sourcetpl=`basename $targetcfg`

   if ! grep -q ^"$tagstr" $targetcfg &>/dev/null; then

    if [ -e "$targetcfg" ]; then
     echo "Backing up $targetcfg to $targetcfg.dpkg-old ..."
     cp $targetcfg $targetcfg.dpkg-old
    fi

    echo "Creating new configfile $targetcfg ..."
    sed -e "s|@@package@@|$package|
            s|@@date@@|$now|
            s|@@radiussecret@@|$radiussecret|
            s|@@ipcopip@@|$ipcopip|
            s|@@ldappassword@@|$ldappassword|
            s|@@basedn@@|$basedn|" $tpldir/$sourcetpl > $targetcfg
    chmod 640 $targetcfg
    chown root:freerad $targetcfg
    radius_restart=yes

   fi # tagstr

  done # targets

  # create dummy snmp.conf
  CONF=/etc/freeradius/snmp.conf
  [ -e "$CONF" ] || touch "$CONF"

  # permissions
  chown freerad:freerad /var/run/freeradius
  chown freerad:freerad /var/log/freeradius -R
  [ -n "$radius_restart" ] && /etc/init.d/freeradius restart

 ;;

 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

