config() {
  NEW="$1"
  OLD="$(dirname $NEW)/$(basename $NEW .new)"
  if [ ! -r $OLD ]; then
    mv $NEW $OLD
  elif [ "$(cat $OLD | md5sum)" = "$(cat $NEW | md5sum)" ]; then
    rm $NEW
  fi
}

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.apparmor.new
config etc/apparmor/easyprof.conf.new
config etc/apparmor/logprof.conf.new
config etc/apparmor/notify.conf.new
config etc/apparmor/parser.conf.new
config etc/apparmor/severity.db.new

# Make rc.apparmor executable. sysvinit silently skips non-executable
# /etc/rc.d/rc.* scripts, so without this the profiles never load.
chmod 755 etc/rc.d/rc.apparmor 2>/dev/null || true


# Reconcile sshd's AppArmor profile with the port sshd actually binds.
#
# net_bind_service is only needed for ports below 1024. AM·OS defaults
# to 62222 port, so the shipped profile drops the capability. If the
# installed sshd_config uses a differnt port, this fixes it.
#
# During install this runs before the installer has written
# /etc/ssh/sshd_config, so it exits quietly and amos-harden does
# the work. On an upgrade of an existing system, sshd_config exists
# and this is the only place the reconciliation happens.
#
# Idempotent.

if [ -f etc/ssh/sshd_config ] && [ -f etc/apparmor.d/sshd ]; then
  port=$(awk '/^Port /{print $2; exit}' etc/ssh/sshd_config 2>/dev/null)
  [ -n "$port" ] || port=62222

  has_cap=0
  grep -qE '^[[:space:]]*capability[[:space:]]+net_bind_service,' etc/apparmor.d/sshd && has_cap=1

  if [ "$port" -lt 1024 ] && [ "$has_cap" = "0" ]; then
    sed -i '0,/^{/s//{\n  capability net_bind_service,/' etc/apparmor.d/sshd
  elif [ "$port" -ge 1024 ] && [ "$has_cap" = "1" ]; then
    sed -i '/^[[:space:]]*capability[[:space:]]\+net_bind_service,/d' etc/apparmor.d/sshd
  fi
fi
