#!/bin/sh

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

  if [ -e "$reference" ] && [ -e "$target" ]; then
    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
}

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
    # IMA-safe: content matches, but only $NEW carries the signature.
    # Apply $OLD's ownership/perms to $NEW, then promote $NEW over $OLD.
    copy_metadata "$OLD" "$NEW"
    mv -f "$NEW" "$OLD"
  fi
  # Otherwise, we leave the .new copy for the admin to consider...
}

# Apply the installed rc.mysqld's permissions to the shipped .new file.
# This preserves both the IMA signature on .new AND any admin-customized
# permissions on the installed copy. The old version used `cat >` which
# truncated and rewrote the file, stripping the security.ima xattr.
if [ -e etc/rc.d/rc.mysqld ]; then
  copy_metadata etc/rc.d/rc.mysqld etc/rc.d/rc.mysqld.new
fi

config etc/rc.d/rc.mysqld.new
config etc/mysqlaccess.conf.new
config etc/my.cnf.new
config etc/my.cnf.d/client.cnf.new
config etc/my.cnf.d/hashicorp_key_management.cnf.new
config etc/my.cnf.d/mysql-clients.cnf.new
config etc/my.cnf.d/s3.cnf.new
config etc/my.cnf.d/server.cnf.new
config etc/my.cnf.d/skip-ssl.cnf.new
config etc/my.cnf.d/spider.cnf.new
config etc/logrotate.d/mariadb.new
config etc/default/mariadb.new

# This one is only comments, so remove it if it's left behind:
if [ -r etc/security/user_map.conf.new ]; then
  config etc/security/user_map.conf.new
fi
rm -f etc/security/user_map.conf.new

# Back up obsolete "mysql" logrotate file to avoid conflict with "mariadb"
# logrotate file:
if [ -f etc/logrotate.d/mysql ]; then
  mv etc/logrotate.d/mysql etc/logrotate.d/mysql.bak
fi