
config() {
  NEW="$1"
  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...
}

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
}

for file in etc/openrc/conf.d/*.new; do
  config "${file}"
done

for file in etc/openrc/local.d/*.new; do
  preserve_perms "${file}"
done

# Enable some basic services
[ ! -e "etc/openrc/runlevels/sysinit/udev" ] && ln -s /etc/openrc/init.d/udev "etc/openrc/runlevels/sysinit/udev"
[ ! -e "etc/openrc/runlevels/sysinit/udev-trigger" ] && ln -s /etc/openrc/init.d/udev-trigger "etc/openrc/runlevels/sysinit/udev-trigger"
[ ! -e "etc/openrc/runlevels/boot/fuse" ] && ln -s /etc/openrc/init.d/fuse "etc/openrc/runlevels/boot/fuse"
[ ! -e "etc/openrc/runlevels/boot/sysklogd" ] && ln -s /etc/openrc/init.d/sysklogd "etc/openrc/runlevels/boot/sysklogd"
[ ! -e "etc/openrc/runlevels/default/dbus" ] && ln -s /etc/openrc/init.d/dbus "etc/openrc/runlevels/default/dbus"
[ ! -e "etc/openrc/runlevels/boot/zram" ] && ln -s /etc/openrc/init.d/zram "etc/openrc/runlevels/boot/zram"

# disable udev-postmount
[ -e "etc/openrc/runlevels/sysinit/udev-postmount" ] && rm -v "etc/openrc/runlevels/sysinit/udev-postmount"

# disable kmod-static-nodes (openrc-0.26.1, 2017-05-14)
[ -e "etc/openrc/runlevels/sysinit/kmod-static-nodes" ] && rm -v "etc/openrc/runlevels/sysinit/kmod-static-nodes"

# maintain compatibilty with previous xdm script
ln -sf /usr/bin/startDM "etc/X11/startDM.sh"
