#!/bin/sh

# Helper to emulate --reference for BusyBox compatibility
copy_metadata() {
  reference="$1"
  target="$2"

  if [ -e "$reference" ] && [ -e "$target" ]; then
    # Get numeric UID:GID and octal permissions
    owner=$(stat -c "%u:%g" "$reference" 2>/dev/null)
    perm=$(stat -c "%a" "$reference" 2>/dev/null)

    if [ -n "$owner" ]; then
      chown "$owner" "$target" 2>/dev/null || true
    fi
    if [ -n "$perm" ]; then
      chmod "$perm" "$target" 2>/dev/null || true
    fi
  fi
}

# 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
      copy_metadata "$OLD" "$NEW"
      mv -f "$NEW" "$OLD"
    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
    # Copy the signed NEW file to .incoming (preserves the IMA xattr)
    cp -a "$NEW" "${NEW}.incoming"

    # Apply the old file's metadata to the incoming file
    copy_metadata "$OLD" "${NEW}.incoming"

    mv -f "${NEW}.incoming" "$NEW"
  fi
  config "$NEW"
}

# Prepare the new configuration files
for file in etc/profile.d/libglib2.csh.new etc/profile.d/libglib2.sh.new ; do
  if test -e $(dirname $file)/$(basename $file .new) ; then
    if [ ! -x $(dirname $file)/$(basename $file .new) ]; then
      chmod 644 $file
     else
      chmod 755 $file
    fi
  fi
  config $file
done

# Try to run these. If they fail, no biggie.
chroot . /usr/bin/glib-compile-schemas /usr/share/glib-2.0/schemas/ 1> /dev/null 2> /dev/null || true
chroot . /usr/bin/gio-querymodules @LIBDIR@/gio/modules/ 1> /dev/null 2> /dev/null || true
