# 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/profile.d/flatpak.sh.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 '372' group if it doesn't exist already:
/usr/sbin/groupadd -g 372 flatpak 2> /dev/null

# Add the '372' user if it doesn't exist already:
/usr/sbin/useradd -c "Flatpak system helper" -d /var/lib/flatpak -M \
  -s "/bin/false" -g 372 -u 372 flatpak 2> /dev/null
EOR

# Make the flathub repository available to root:
chroot .   /usr/bin/flatpak remote-add --if-not-exists   flathub /etc/flatpak/remotes.d/flathub.flatpakrepo
# Inform the user about adding flatpak to their homedirectory:
echo "NOTE:"
echo ">> you can add the FlatHub repository for your own user if you do not want to use the 'root' account, by executing the following command:"
echo ">> flatpak --user remote-add --if-not-exists flathub /etc/flatpak/remotes.d/flathub.flatpakrepo"
echo ">> In general, add '--user' to any flatpak command to make it apply to your own personal environment."
echo ""
( cd usr/lib ; rm -rf libflatpak.so )
( cd usr/lib ; ln -sf libflatpak.so.0.11207.0 libflatpak.so )
( cd usr/lib ; rm -rf libflatpak.so.0 )
( cd usr/lib ; ln -sf libflatpak.so.0.11207.0 libflatpak.so.0 )
