# 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.anubis.new
config etc/anubis/default.env.new
config etc/logrotate.d/anubis.new

# 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 '390' group if it doesn't exist already:
/usr/sbin/groupadd -g 390 anubis 2> /dev/null

# Add the '390' user if it doesn't exist already:
/usr/sbin/useradd -c "Anubis Web AI Firewall" -d /var/run/anubis -M \
  -s "/bin/false" -g 390 -u 390 anubis 2> /dev/null
EOR

# Update rc.local so that Anubis daemon will be started on boot
if ! grep "rc.anubis" etc/rc.d/rc.local 1>/dev/null 2>&1 ; then
  cat <<_EOM_ >> etc/rc.d/rc.local

if [ -x /etc/rc.d/rc.anubis ]; then
  # Start Anubis Web AI Firewall
  echo "Starting Anubis WAF daemon:    /etc/rc.d/rc.anubis start"
  /etc/rc.d/rc.anubis start
fi
_EOM_
fi

