# Handle the incoming configuration files:
config() {
  for infile in $1; do
    NEW="$infile"
    OLD="`dirname $NEW`/`basename $NEW .new`"
    # If there's no config file by that name, mv it over:
    if [ ! -r $OLD ]; then
      mv $NEW $OLD
    elif [ "`cat $OLD | md5sum`" = "`cat $NEW | md5sum`" ]; then
      # toss the redundant copy
      rm $NEW
    fi
    # Otherwise, we leave the .new copy for the admin to consider...
  done
}

preserve_perms() {
  NEW="$1"
  OLD="$(dirname $NEW)/$(basename $NEW .new)"
  if [ -e $OLD ]; then
    cp -a $OLD ${NEW}.incoming
    cat $NEW > ${NEW}.incoming
    mv ${NEW}.incoming $NEW
  fi
  config $NEW
}

preserve_perms etc/rc.d/rc.clamav.new
config etc/freshclam.conf.new
config etc/clamd.conf.new
config etc/clamav-milter.conf.new
config etc/logrotate.d/clamav.new

# Create log files
touch var/log/clamav/clamd.log
touch var/log/clamav/freshclam.log

# Only way to create and use the correct uid and gid on the target system,
# is to use chroot:
chroot . <<EOR 2>/dev/null
# Add the 'clamav' group if it doesn't already exist:
# Actually, the use of "amavis" group is for compatibility with amavisd-new.
/usr/sbin/groupadd clamav 2> /dev/null
# Add the 'clamav' user if it doesn't already exist:
/usr/sbin/useradd -c "ClamAV user"  \
  -g clamav -s "/bin/false" clamav 2> /dev/null

# Restore the correct permissions
chown clamav usr/sbin/clamav-milter
chmod 4700 usr/sbin/clamav-milter
chown -R clamav:clamav var/run/clamav
chmod 771 var/run/clamav
chown -R clamav:clamav var/log/clamav
chmod 770 var/log/clamav
chmod 660 var/log/clamav/*.log
chown -R clamav:clamav usr/share/clamav
chmod 770 usr/share/clamav
chmod 660 usr/share/clamav/*
EOR

( cd usr/lib ; rm -rf libclammspack.so )
( cd usr/lib ; ln -sf libclammspack.so.0.1.0 libclammspack.so )
( cd usr/lib ; rm -rf libclamunrar_iface.so.7 )
( cd usr/lib ; ln -sf libclamunrar_iface.so.7.1.1 libclamunrar_iface.so.7 )
( cd usr/lib ; rm -rf libclamav.so.7 )
( cd usr/lib ; ln -sf libclamav.so.7.1.1 libclamav.so.7 )
( cd usr/lib ; rm -rf libclamunrar.so.7 )
( cd usr/lib ; ln -sf libclamunrar.so.7.1.1 libclamunrar.so.7 )
( cd usr/lib ; rm -rf libclamunrar_iface.so )
( cd usr/lib ; ln -sf libclamunrar_iface.so.7.1.1 libclamunrar_iface.so )
( cd usr/lib ; rm -rf libclamunrar.so )
( cd usr/lib ; ln -sf libclamunrar.so.7.1.1 libclamunrar.so )
( cd usr/lib ; rm -rf libclammspack.so.0 )
( cd usr/lib ; ln -sf libclammspack.so.0.1.0 libclammspack.so.0 )
( cd usr/lib ; rm -rf libclamav.so )
( cd usr/lib ; ln -sf libclamav.so.7.1.1 libclamav.so )
