# 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.pesign.new
config etc/pesign/groups.new
config etc/pesign/users.new

# Create 'pesign' user and group on target host:
chroot .   getent group pesign > /dev/null ||     /usr/sbin/groupadd -g 369 -r pesign 2>/dev/null
chroot .   getent passwd pesign > /dev/null ||     /usr/sbin/useradd -c "PE signing daemon" -g pesign     -s /bin/bash -u 369 -r pesign 2>/dev/null

# Give the NSS database directory proper ownership:
chroot .   chown pesign:pesign etc/pki/pesign

# Pesign does not come with a preconfigured NSS database. On startup, pesign
# would abort with error "pesign could not open nss database: bad database".
# If none exists yet, create an initial empty database without password.
# NOTE: for production usage you would set a password on this database
#       using the command "certutil -d sql:/etc/pki/pesign -W"!
if [ ! -f etc/pki/pesign/cert?*.db ]; then
  chroot .     su - pesign -c "certutil -N -d sql:/etc/pki/pesign --empty-password"
fi

# Update rc.local so that pesign will be started on boot:
if ! grep -q "rc.pesign" etc/rc.d/rc.local ; then
  cat <<_EOM_ >> etc/rc.d/rc.local
if [ -x /etc/rc.d/rc.pesign ]; then
  # Start PE signing daemon:
  echo "Starting PE signing daemon:  /etc/rc.d/rc.pesign start"
  /etc/rc.d/rc.pesign start
fi
_EOM_
fi

