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

#COMMON-FUNCTIONS#

case "$1" in
  configure)
  
  DATABASEDIR=/var/lib/clamav
  LOGDIR=/var/log/clamav
  user=clamav
  
  # Set up the clamav user on new install
  if [ -z "$2" ]; then
    adduser --system --no-create-home --quiet \
        --disabled-password --disabled-login \
	--shell /bin/false --group --home /var/lib/clamav clamav
    chown $user:$user $DATABASEDIR
    chown $user:$user $LOGDIR
  else
    if [ -e '/etc/clamav/clamd.conf' ]; then # Upgrade - clamd.conf already there
      clamconf='/etc/clamav/clamd.conf'
    fi
    if dpkg --compare-versions $2 lt 0.93~; then
      rm -rf /var/lib/clamav/main.cvd /var/lib/clamav/main.inc /var/lib/clamav/daily.cvd /var/lib/clamav/daily.inc
    fi
  fi
  
  if [ -f /etc/aliases ] || [ -L /etc/aliases ]; then
    if ! grep -qi "^clamav" /etc/aliases; then
      echo "clamav: root" >> /etc/aliases
      newal=`which newaliases || true`
      if [ -n "$newal" ] && [ -x "$newal" ]; then
        $newal || true
      fi
    fi
  fi
  
  if [ -n "$clamconf" ]; then 
    user="$(grep '^User ' $clamconf | awk '{print $2}')"
    [ -z "$user" ] && user=clamav # Old default config
    data="$(grep '^DatabaseDirectory ' $clamconf | awk '{print $2}')"
    if [ -n "$data" ]; then
      datadir="$(dirname "${data}/.")"
    else
      datadir="$DATABASEDIR"
    fi
    log="$(grep '^LogFile ' $clamconf | awk '{print $2}')"
    if [ -n "$log" ]; then
      logdir=`dirname "$log"`
    else
      logdir="$LOGDIR"
    fi
    
    if [ "$datadir" = "$DATABASEDIR" ] && [ "$logdir" = "$LOGDIR" ]; then
      if [ "$user" = 'clamav' ]; then # Default config
	[ ! -d $DATABASEDIR ] || chown $user:$user $DATABASEDIR || true
	[ ! -d $LOGDIR ]      || chown $user:$user $LOGDIR      || true
      fi
    fi
  else 
    [ ! -d $DATABASEDIR ] || chown $user:$user $DATABASEDIR || true
    [ ! -d $LOGDIR ]      || chown $user:$user $LOGDIR      || true        
  fi

  DEBCONFFILE=/var/lib/clamav/clamav.conf
  DEBROTATEFILE=/var/lib/clamav/clamdrotate.debconf
  CLAMAVCONF=/etc/clamav/clamd.conf
  
  db_metaget clamav-base/debconf value || true
  if [ "$RET" = "true" ]; then
    db_metaget clamav-base/User value || true
    user="$RET"
    db_metaget clamav-base/AddGroups value|| true
    addgroups="$RET"
    db_metaget clamav-base/TcpOrLocal value || true
    if [ "$RET" = "TCP" ]; then
      sock="tcp"
      db_get clamav-base/TCPSocket || true
      tcpsock="$RET"
      db_get clamav-base/TCPAddr
      tcpadd="$RET"
    else
      sock="unix"
      db_metaget clamav-base/LocalSocket value || true
      localsock="$RET"
      db_metaget clamav-base/FixStaleSocket value || true
      fixstale="$RET"
    fi
    db_metaget clamav-base/ScanMail value || true
    scanmail="$RET"
    db_metaget clamav-base/ScanArchive value || true
    scanarchive="$RET"
    db_get clamav-base/MaxDirectoryRecursion || true
    if [ "$RET" != "0" ]; then
      maxdirrec="$RET"
      db_get clamav-base/FollowDirectorySymlinks || true
      followdirsyms="$RET"
    else
      maxdirrec=15
      followdirsyms=false
    fi
    db_metaget clamav-base/FollowFileSymlinks value || true
    followfilesyms="$RET"
    db_get clamav-base/ThreadTimeout || true
    threadtimeout="$RET"
    db_get clamav-base/ReadTimeout || true
    readtimeout="$RET"
    [ -z "$readtimeout" ] && readtimeout="$threadtimeout"
    db_get clamav-base/MaxThreads || true
    maxthreads="$RET"
    db_get clamav-base/MaxConnectionQueueLength || true
    maxconnQleng="$RET"
    db_get clamav-base/StreamMaxLength || true
    [ "$RET" != "0" ] && streamsavelength="$RET"
    db_metaget clamav-base/LogSyslog value || true
    logsyslog="$RET"
    db_get clamav-base/LogFile || true
    if [ "$RET" != "" ]; then
      logfile="$RET"
      db_metaget clamav-base/LogTime value || true
      logtime="$RET"
    fi
    db_get clamav-base/SelfCheck || true
    selfcheck="$RET"

    slurp_config "$CLAMAVCONF"
    
    if [ -z "$PidFile" ]; then
      PidFile='/var/run/clamav/clamd.pid'
    elif [ "$PidFile" = '/var/run/clamd.pid' ]; then
      PidFile='/var/run/clamav/clamd.pid'
    fi
    
    [ -z "$DatabaseDirectory" ] && DatabaseDirectory='/var/lib/clamav'
    
    if [ -z "$2" ]; then # Fresh install
      [ -z "$AllowSupplementaryGroups" ] && AllowSupplementaryGroups=true
    elif [ -n "$addgroups" ]; then 
      AllowSupplementaryGroups=true
    fi

    echo "#Automatically Generated by clamav-base postinst" > $DEBCONFFILE
    echo "#To reconfigure clamd run #dpkg-reconfigure clamav-base" >> $DEBCONFFILE
    echo "#Please read /usr/share/doc/clamav-base/README.Debian.gz for details" >> $DEBCONFFILE
    if [ "$sock" = "tcp" ]; then
      echo "TCPSocket $tcpsock" >> $DEBCONFFILE
      [ "$tcpadd" = "any" ] || echo "TCPAddr $tcpadd" >> $DEBCONFFILE
    else
      echo "LocalSocket $localsock" >> $DEBCONFFILE
      echo "FixStaleSocket $fixstale" >> $DEBCONFFILE
    fi
    [ -z "$user" ] && user=clamav
    [ -z "$AllowSupplementaryGroups" ] && AllowSupplementaryGroups=false
    [ -z "$ArchiveBlockEncrypted" ] && ArchiveBlockEncrypted="$ArchiveDetectEncrypted"
    [ -z "$ArchiveBlockEncrypted" ] && ArchiveBlockEncrypted=false
    [ -z "$maxdirrec" ] && maxdirrec=15
    [ -z "$readtimeout" ] && readtimeout=120
    [ -z "$maxthreads" ] && maxthreads=10
    [ -z "$maxconnQleng" ] && maxconnQleng=15
    [ -z "$streamsavelength" ] && streamsavelength=10
    [ -z "$LogFacility" ] && LogFacility=LOG_LOCAL6
    [ -z "$LogFileUnlock" ] && LogFileUnlock=false
    [ -z "$LogFileMaxSize" ] && LogFileMaxSize=0
    [ -z "$LogClean" ] && LogClean=false
    [ -z "$LogVerbose" ] && LogVerbose=false
    [ -z "$selfcheck" ] && selfcheck=1800
    [ -z "$Foreground" ] && Foreground=false
    [ -z "$Debug" ] && Debug=false
    if [ -n "$DisableDefaultScanOptions" ]; then
      # Upgrade from < 0.9x
      [ -z "$ScanPE" ] && ScanPE=false
      [ -z "$ScanOLE2" ] && ScanOLE2=false
      [ -z "$ScanHTML" ] && ScanHTML=false
      [ -z "$ScanPDF" ] && ScanPDF=false
    else
      [ -z "$ScanPE" ] && ScanPE=true
      [ -z "$ScanOLE2" ] && ScanOLE2=true
      [ -z "$ScanHTML" ] && ScanHTML=true
      [ -z "$ScanPDF" ] && ScanPDF=true
    fi
    [ -z "$DetectBrokenExecutables" ] && DetectBrokenExecutables=false
    [ -z "$MailFollowURLs" ] && MailFollowURLs=false
    [ -z "$ExitOnOOM" ] && ExitOnOOM=false
    [ -z "$LeaveTemporaryFiles" ] && LeaveTemporaryFiles=false
    [ -z "$AlgorithmicDetection" ] && AlgorithmicDetection=true
    [ -z "$ScanELF" ] && ScanELF=true
    [ -z "$IdleTimeout" ] && IdleTimeout=30
    [ -z "$PhishingSignatures" ] && PhishingSignatures=true
    [ -z "$PhishingScanURLs" ] && PhishingScanURLs=true
    [ -z "$PhishingAlwaysBlockSSLMismatch" ] && PhishingAlwaysBlockSSLMismatch=false
    [ -z "$PhishingAlwaysBlockCloak" ] && PhishingAlwaysBlockCloak=false
    [ -z "$DetectPUA" ] && DetectPUA=false
    [ -z "$MaxScanSize" ] && MaxScanSize=100M
    [ -z "$MaxFileSize" ] && MaxFileSize=25M
    [ -z "$MaxRecursion" ] && MaxRecursion=10
    [ -z "$MaxFiles" ] && MaxFiles=10000
    [ -z "$ExcludePUA" ] && ExcludePUA=
    [ -z "$IncludePUA" ] && IncludePUA=
    [ -z "$ScanPartialMessages" ] && ScanPartialMessages=false
    [ -z "$HeuristicScanPrecedence" ] && HeuristicScanPrecedence=false
    [ -z "$StructuredDataDetection" ] && StructuredDataDetection=false
    [ -z "$CommandReadTimeout" ] && CommandReadTimeout=5
    [ -z "$SendBufTimeout" ] && SendBufTimeout=200
    [ -z "$MaxQueue" ] && MaxQueue=100

    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

    cat >> $DEBCONFFILE << EOF
User $user
AllowSupplementaryGroups $AllowSupplementaryGroups
ScanMail $scanmail
ScanArchive $scanarchive
ArchiveBlockEncrypted $ArchiveBlockEncrypted
MaxDirectoryRecursion $maxdirrec
FollowDirectorySymlinks $followdirsyms
FollowFileSymlinks $followfilesyms
ReadTimeout $readtimeout
MaxThreads $maxthreads
MaxConnectionQueueLength $maxconnQleng
StreamMaxLength ${streamsavelength}M
LogSyslog $logsyslog
LogFacility $LogFacility
LogClean $LogClean
LogVerbose $LogVerbose
PidFile $PidFile
DatabaseDirectory $DatabaseDirectory
SelfCheck $selfcheck
Foreground $Foreground
Debug $Debug
ScanPE $ScanPE
ScanOLE2 $ScanOLE2
ScanHTML $ScanHTML
DetectBrokenExecutables $DetectBrokenExecutables
MailFollowURLs $MailFollowURLs
ExitOnOOM $ExitOnOOM
LeaveTemporaryFiles $LeaveTemporaryFiles
AlgorithmicDetection $AlgorithmicDetection
ScanELF $ScanELF
IdleTimeout $IdleTimeout
PhishingSignatures $PhishingSignatures
PhishingScanURLs $PhishingScanURLs
PhishingAlwaysBlockSSLMismatch $PhishingAlwaysBlockSSLMismatch
PhishingAlwaysBlockCloak $PhishingAlwaysBlockCloak
DetectPUA $DetectPUA
ScanPartialMessages $ScanPartialMessages
HeuristicScanPrecedence $HeuristicScanPrecedence
StructuredDataDetection $StructuredDataDetection
CommandReadTimeout $CommandReadTimeout
SendBufTimeout $SendBufTimeout
MaxQueue $MaxQueue
EOF

    if is_true "$StructuredDataDetection"; then
      [ -z "$StructuredMinCreditCardCount" ] || StructuredMinCreditCardCount=3
      [ -z "$StructuredMinSSNCount" ] || StructuredMinSSNCount=3
      [ -z "$StructuredSSNFormatNormal" ] || StructuredSSNFormatNormal=true
      [ -z "$StructuredSSNFormatStripped" ] || StructuredSSNFormatStripped=false
      cat >> $DEBCONFFILE << EOF
StructuredMinCreditCardCount $StructuredMinCreditCardCount
StructuredMinSSNCount $StructuredMinSSNCount
StructuredSSNFormatNormal $StructuredSSNFormatNormal
StructuredSSNFormatStripped $StructuredSSNFormatStripped
EOF
    fi

    if [ -n "$IncludePUA" ]; then
      for i in $IncludePUA; do
        echo "IncludePUA $i" >> $DEBCONFFILE
      done
    fi
    if [ -n "$ExcludePUA" ]; then
      for e in $ExcludePUA; do
        echo "ExcludePUA $i" >> $DEBCONFFILE
      done
    fi
    if [ -n "$logfile" ]; then
      echo "LogFile $logfile" >> $DEBCONFFILE
      echo "LogTime $logtime" >> $DEBCONFFILE
      echo "LogFileUnlock $LogFileUnlock" >> $DEBCONFFILE
      echo "LogFileMaxSize $LogFileMaxSize" >> $DEBCONFFILE
    fi

    [ -n "$VirusEvent" ] && echo "VirusEvent $VirusEvent" >> $DEBCONFFILE
    [ -n "$StreamMinPort" ] && echo "StreamMinPort $StreamMinPort" >> $DEBCONFFILE
    [ -n "$StreamMaxPort" ] && echo "StreamMaxPort $StreamMaxPort" >> $DEBCONFFILE
    [ -n "$ClamukoScanOnAccess" ] && echo "ClamukoScanOnAccess $ClamukoScanOnAccess" >> $DEBCONFFILE
    [ -n "$ClamukoScanOnOpen" ] && echo "ClamukoScanOnOpen $ClamukoScanOnOpen" >> $DEBCONFFILE
    [ -n "$ClamukoScanOnClose" ] && echo "ClamukoScanOnClose $ClamukoScanOnClose" >> $DEBCONFFILE
    [ -n "$ClamukoScanOnExec" ] && echo "ClamukoScanOnExec $ClamukoScanOnExec" >> $DEBCONFFILE
    [ -n "$ClamukoIncludePath" ] && echo "ClamukoIncludePath $ClamukoIncludePath" >> $DEBCONFFILE
    [ -n "$ClamukoIncludePath" ] && echo "ClamukoIncludePath $ClamukoIncludePath" >> $DEBCONFFILE
    [ -n "$ClamukoExcludePath" ] && echo "ClamukoExcludePath $ClamukoExcludePath" >> $DEBCONFFILE
    [ -n "$ClamukoMaxFileSize" ] && echo "ClamukoMaxFileSize $ClamukoMaxFileSize" >> $DEBCONFFILE
    
    ucf_cleanup "$CLAMAVCONF"
    ucf_upgrade_check "$CLAMAVCONF" "$DEBCONFFILE" /var/lib/ucf/cache/:etc:clamav:clamd.conf
    rm -f "$DEBCONFFILE"

    db_stop || true
    
    if [ -n "$addgroups" ]; then
      for group in $addgroups; do
        id "$user" | grep -q "$group" || adduser "$user" "$group"
      done
    fi
    
  else
    ucf_cleanup "$CLAMAVCONF"
    ucf_upgrade_check "$CLAMAVCONF" /usr/share/doc/clamav-base/examples/clamd.conf /var/lib/ucf/cache/:etc:clamav:clamd.conf

    db_stop || true
  fi

  # Update database now
  for db in main daily; do
    if [ ! -e "$DATABASEDIR"/"$db".cvd ] && [ ! -d "$DATABASEDIR"/"$db".inc ] && [ ! -e "$DATABASEDIR"/"$db".cld ]; then
      install -m 0644 -o $user -g $user /usr/share/doc/clamav-base/examples/"$db".cvd \
        "$DATABASEDIR"
    fi
  done

  chmod 644 $CLAMAVCONF || true
  chown root:root $CLAMAVCONF || 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
