#! /bin/sh
# 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>
#        * <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
#
# quoting from the policy:
#     Any necessary prompting should almost always be confined to the
#     post-installation script, and should be protected with a conditional
#     so that unnecessary prompting doesn't happen if a package's
#     installation fails and the `postinst' is called with `abort-upgrade',
#     `abort-remove' or `abort-deconfigure'.

#loading debconf module
. /usr/share/debconf/confmodule

to_lower()
{
  word="$1"
  lcword=$(echo "$word" | tr A-Z a-z)
  echo "$lcword"
}

is_true()
{
  var="$1"
  lcvar=$(to_lower "$var")
  [ 'true' = "$lcvar" ] || [ 'yes' = "$lcvar" ] || [ 1 = "$lcvar" ]
  return $?
}

ucf_cleanup()
{
  # This only does something if I've fucked up before
  # Not entirely impossible :(

  configfile=$1

  if [ `grep "$configfile" /var/lib/ucf/hashfile | wc -l` -gt 1 ]; then
    grep -v "$configfile" /var/lib/ucf/hashfile > /var/lib/ucf/hashfile.tmp
    grep "$configfile" /var/lib/ucf/hashfile | tail -n 1  >> /var/lib/ucf/hashfile.tmp
    mv /var/lib/ucf/hashfile.tmp /var/lib/ucf/hashfile
  fi
}

add_to_ucf()
{
  configfile=$1
  ucffile=$2

  if ! grep -q "$configfile" /var/lib/ucf/hashfile; then
    md5sum $configfile >> /var/lib/ucf/hashfile
    cp $configfile $ucffile
  fi
}

ucf_upgrade_check()
{
  configfile=$1
  sourcefile=$2
  ucffile=$3

  if [ -f "$configfile" ]; then
    add_to_ucf $configfile $ucffile
    ucf --three-way --debconf-ok "$sourcefile" "$configfile"
  else
    [ -d /var/lib/ucf/cache ] || mkdir -p /var/lib/ucf/cache
    cp $sourcefile $configfile
    add_to_ucf $configfile $ucffile
  fi
}

slurp_config()
{
  CLAMAVCONF="$1"
  
  if [ -e "$CLAMAVCONF" ]; then
    for variable in `egrep -v '^[[:space:]]*(#|$)' "$CLAMAVCONF" | awk '{print $1}'`; do
      if [ "$variable" = 'DatabaseMirror' ]; then
        if [ -z "$DatabaseMirror" ]; then
          for i in `grep ^$variable $CLAMAVCONF | awk '{print $2}'`; do
            value="$i $value"
          done
        else
          continue
        fi
      elif [ "$variable" = 'IncludePUA' ]; then
        if [ -z "$IncludePUA" ]; then
          for i in `grep ^$variable $CLAMAVCONF | awk '{print $2}'`; do
            value="$i $value"
          done
        else
          continue
        fi
      elif [ "$variable" = 'ExcludePUA' ]; then
        if [ -z "$ExcludePUA" ]; then
          for i in `grep ^$variable $CLAMAVCONF | awk '{print $2}'`; do
            value="$i $value"
          done
        else
          continue
        fi
      elif [ "$variable" = 'VirusEvent' ] || [ "$variable" = 'OnUpdateExecute' ] || [ "$variable" = 'OnErrorExecute' ]; then
        value=`grep ^$variable $CLAMAVCONF | head -n1 | sed -e s/$variable\ //`
      else
        value=`grep ^$variable $CLAMAVCONF | head -n1 | awk '{print $2}'`
      fi
      if [ -z "$value" ]; then 
        export "$variable"="true"
      elif [ "$value" != "$variable" ]; then
        export "$variable"="$value"
      else
        export "$variable"="true"
      fi
      unset value
    done
  fi
}

make_dir()
{
  DIR=$1
  if [ -d "$DIR" ]; then
    return 0;
  fi
  [ -n "$User" ] || User=clamav
  mkdir -p -m 0755 "$DIR"
  chown "$User:$User" "$DIR"
}



case "$1" in
  configure)

  CLAMAVMILTERCONF=/etc/clamav/clamav-milter.conf
  DEBROTATEFILE=/var/lib/clamav/clamav-milter.rotate.debconf
  CLAMAVROTATEFILE=/etc/logrotate.d/clamav-milter
  DEBCONFFILE=/var/lib/clamav/clamav-milter.conf
  
  db_metaget clamav-milter/debconf value || true
  if [ "$RET" = "true" ]; then
    db_metaget clamav-milter/MilterSocket value || true
    MilterSocket="$RET"
    db_metaget clamav-milter/FixStaleSocket value || true
    FixStaleSocket="$RET"
    db_metaget clamav-milter/User value || true
    User="$RET"
    db_metaget clamav-milter/AddGroups value || true
    AddGroups="$RET"
    db_metaget clamav-milter/ReadTimeout value || true
    ReadTimeout="$RET"
    db_metaget clamav-milter/Foreground value || true
    Foreground="$RET"
    db_metaget clamav-milter/Chroot value || true
    Chroot="$RET"
    db_metaget clamav-milter/PidFile value || true
    PidFile="$RET"
    db_metaget clamav-milter/TemporaryDirectory value || true
    TemporaryDirectory="$RET"
    db_metaget clamav-milter/ClamdSocket value || true
    ClamdSocket="$RET"
    db_metaget clamav-milter/LocalNet value || true
    LocalNet="$RET"
    db_metaget clamav-milter/Whitelist value || true
    Whitelist="$RET"
    db_metaget clamav-milter/OnClean value || true
    OnClean="$RET"
    db_metaget clamav-milter/OnInfected value || true
    OnInfected="$RET"
    db_metaget clamav-milter/OnFail value || true
    OnFail="$RET"
    db_metaget clamav-milter/RejectMsg value || true
    RejectMsg="$RET"
    db_metaget clamav-milter/AddHeader value || true
    AddHeader="$RET"
    db_metaget clamav-milter/LogFile value || true
    LogFile="$RET"
    db_metaget clamav-milter/LogFileUnlock value || true
    LogFileUnlock="$RET"
    db_metaget clamav-milter/LogFileMaxSize value || true
    LogFileMaxSize="${RET}M"
    db_metaget clamav-milter/LogTime value || true
    LogTime="$RET"
    db_metaget clamav-milter/LogSyslog value || true
    LogSyslog="$RET"
    db_metaget clamav-milter/LogFacility value || true
    LogFacility="$RET"
    db_metaget clamav-milter/LogVerbose value || true
    LogVerbose="$RET"
    db_metaget clamav-milter/LogInfected value || true
    LogInfected="$RET"
    db_metaget clamav-milter/MaxFileSize value || true
    maxfilesize="`echo $RET | sed -e s/M//g`"
    MaxFileSize="${maxfilesize}M"

    if [ -z "$LogFile" ] || [ "$LogFile" = 'none' ]; then
      LogSyslog=true
    fi

    slurp_config "$CLAMAVMILTERCONF"
    
    echo "#Automatically Generated by clamav-milter postinst" > $DEBCONFFILE
    echo "#To reconfigure clamav-milter run #dpkg-reconfigure clamav-milter" >> $DEBCONFFILE
    echo "#Please read /usr/share/doc/clamav-base/README.Debian.gz for details" >> $DEBCONFFILE
    [ -z "$MilterSocket" ] && MilterSocket="/var/run/clamav/milter.ctl"
    [ -z "$FixStaleSocket" ] && FixStaleSocket="true"
    [ -z "$User" ] && User=clamav
    [ -z "$AllowSupplementaryGroups" -o -n "$AddGroups" ] && AllowSupplementaryGroups=true
    [ -z "$ReadTimeout" ] && ReadTimeout="120"
    [ -z "$Foreground" ] && Foreground="false"
    [ -z "$PidFile" ] && PidFile="/var/run/clamav/clamav-milter.pid"
    [ -z "$ClamdSocket" ] && ClamdSocket="unix:/var/run/clamav/clamd.ctl"
    [ -z "$OnClean" ] && OnClean="Accept"
    [ -z "$OnInfected" ] && OnInfected="Quarantine"
    [ -z "$OnFail" ] && OnFail="Defer"
    [ -z "$AddHeader" ] && AddHeader="false"
    [ -z "$LogSyslog" ] && LogSyslog="false"
    [ -z "$LogFacility" ] && LogFacility="LOG_LOCAL6"
    [ -z "$LogVerbose" ] && LogVerbose="false"
    [ -z "$LogInfected" ] && LogInfected="Off"
    [ -z "$MaxFileSize" ] && MaxFileSize="25M"

    cat >> $DEBCONFFILE << EOF
MilterSocket $MilterSocket
FixStaleSocket $FixStaleSocket
User $User
AllowSupplementaryGroups $AllowSupplementaryGroups
ReadTimeout $ReadTimeout
Foreground $Foreground
PidFile $PidFile
ClamdSocket $ClamdSocket
OnClean $OnClean
OnInfected $OnInfected
OnFail $OnFail
AddHeader $AddHeader
LogSyslog $LogSyslog
LogFacility $LogFacility
LogVerbose $LogVerbose
LogInfected $LogInfected
MaxFileSize $MaxFileSize
EOF
    if [ -n "$SkipAuthenticated" ]; then
      cat >> $DEBCONFFILE << EOF
SkipAuthenticated $SkipAuthenticated
EOF
    fi

    if [ -n "$Chroot" ]; then
      cat >> $DEBCONFFILE << EOF
Chroot $Chroot
EOF
    fi

    if [ -n "$LocalNet" ]; then
      cat >> $DEBCONFFILE << EOF
LocalNet $LocalNet
EOF
    fi

    if [ -n "$Whitelist" ]; then
      cat >> $DEBCONFFILE << EOF
Whitelist $Whitelist
EOF
    fi

    if [ -n "$RejectMsg" ]; then
      cat >> $DEBCONFFILE << EOF
RejectMsg $RejectMsg
EOF
    fi

    if [ -n "$TemporaryDirectory" ]; then
	cat >> $DEBCONFFILE << EOF
TemporaryDirectory $TemporaryDirectory
EOF
    else
	cat >> $DEBCONFFILE << EOF
# TemporaryDirectory is not set to its default /tmp here to make overriding
# the default with environment variables TMPDIR/TMP/TEMP possible
EOF
    fi

    if [ -n "$LogFile" ] && [ "$LogFile" != 'none' ]; then
      echo "LogFile $LogFile" >> $DEBCONFFILE
      echo "LogTime $LogTime" >> $DEBCONFFILE
      echo "LogFileUnlock $LogFileUnlock" >> $DEBCONFFILE
      echo "LogFileMaxSize $LogFileMaxSize" >> $DEBCONFFILE
    fi
    
    ucf_cleanup "$CLAMAVMILTERCONF"
    ucf_upgrade_check "$CLAMAVMILTERCONF" "$DEBCONFFILE" /var/lib/ucf/cache/:etc:clamav:clamav-milter.conf
    rm -f "$DEBCONFFILE"

    if [ -n "$AddGroups" ]; then
      for group in $AddGroups; do
        id "$User" | grep -q "$group" || adduser "$User" "$group"
      done
    fi
    
  else
    ucf_cleanup "$CLAMAVMILTERCONF"
    ucf_upgrade_check "$CLAMAVMILTERCONF" /usr/share/doc/clamav-milter/examples/clamav-milter.conf /var/lib/ucf/cache/:etc:clamav:clamav-milter.conf
  fi

  chmod 644 $CLAMAVMILTERCONF || true
  chown root:root $CLAMAVMILTERCONF || true
  
  slurp_config "$CLAMAVMILTERCONF"

  if [ -n "$LogFile" ]; then
    if echo "$LogFile" | grep -q '^/dev/'; then
      make_logrotate=false
    else
      make_logrotate=true
    fi
    [ -n "$User" ] || User=clamav
    if [ "$make_logrotate" = 'true' ]; then
      echo "$LogFile {" > $DEBROTATEFILE
      echo "     rotate 12" >> $DEBROTATEFILE
      echo "     weekly" >> $DEBROTATEFILE
      echo "     compress" >> $DEBROTATEFILE
      echo "     delaycompress" >> $DEBROTATEFILE
      echo "     create 640  $User adm" >> $DEBROTATEFILE
      echo "     postrotate" >> $DEBROTATEFILE
      echo "     /etc/init.d/clamav-milter reload-log > /dev/null" >> $DEBROTATEFILE
      echo "     endscript" >> $DEBROTATEFILE
      echo "     }" >> $DEBROTATEFILE
      touch "$LogFile"
      chown "$User":adm "$LogFile"
      chmod 0640 "$LogFile"
      ucf_cleanup "$CLAMAVROTATEFILE"
      ucf_upgrade_check "$CLAMAVROTATEFILE" "$DEBROTATEFILE" /var/lib/ucf/cache/:etc:logrotate.d:clamav-milter
      rm -f $DEBROTATEFILE
    else
      if [ -e "$CLAMAVROTATEFILE" ]; then
        echo "Disabling old logrotate script for clamav-milter"
        mv "$CLAMAVROTATEFILE" "$CLAMAVROTATEFILE".dpkg-old
        ucf -p "$CLAMAVROTATEFILE"
      fi
    fi
  else
    if [ -e "$CLAMAVROTATEFILE" ]; then
      echo "Disabling old logrotate script for clamav-milter"
      mv "$CLAMAVROTATEFILE" "$CLAMAVROTATEFILE".dpkg-old
      ucf -p "$CLAMAVROTATEFILE"
    fi
  fi
  db_stop || 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
