#!/bin/bash
# amos-harden -- AM·OS post-install configuration and hardening.
#
# Runs as root on the target system, after install.sh has unpacked
# packages and populated /home/annode. Safe to re-run.
#
#   amos-harden --check    report only, make no changes
#   amos-harden --apply    fix deviations (default)
#
# Env:
#   HARDEN_ACCOUNT_DEFAULTS=no    report login.defs policy values but
#                                 leave the file untouched.
#                                 Default: yes -- apply them.
#
#
# Both were called by install.sh via chroot. Merging them means one
# call site, one log, one place to look when something drifts.
#
# Design:
#  - Fixes only rules with an unambiguous right answer.
#  - Reports anything whose correct state depends on admin intent.
#  - Never uses chattr +i (breaks package upgrades and passwd changes).
#  - Never removes setuid from the baseline set.
#  - Symlinks are never chmod'd or chown'd -- stat on a symlink reports
#    the link's own mode (777), which would produce false deviations on
#    every run for /boot/vmlinuz, System.map, config, etc.

set -eu

MODE="${1:---apply}"
LOG="/var/log/amos-post-install.log"
HARDEN_ACCOUNT_DEFAULTS="${HARDEN_ACCOUNT_DEFAULTS:-yes}"

DO_STRIP=1
for arg in "$@"; do
    [ "$arg" = "--no-strip" ] && DO_STRIP=0
done

ISO_PROFILE="${2:-}"
if [ -z "$ISO_PROFILE" ] && [ -f /etc/amos/edition ]; then
    ISO_PROFILE=$(cat /etc/amos/edition)
fi

ISO_PROFILE=$(echo "$ISO_PROFILE" | tr -d '[:space:]')

case "$MODE" in
  --apply) DRY=0 ;;
  --check) DRY=1 ;;
  *) echo "usage: $0 [--check|--apply]" >&2; exit 2 ;;
esac

: > "$LOG"

log()  { printf '[%s] %s\n' "$(date '+%H:%M:%S')" "$*" | tee -a "$LOG"; }
warn() { printf '[%s] WARN: %s\n' "$(date '+%H:%M:%S')" "$*" | tee -a "$LOG"; }

do_fix() {
  if [ "$DRY" = "1" ]; then
    log "WOULD: $*"
  else
    log "FIX:   $*"
    "$@" 2>/dev/null || warn "command failed: $*"
  fi
}

# Apply chown/chmod only if current state differs.
# Skips symlinks -- stat on a symlink reports the link's own mode (777),
# which is never what we want to enforce.
fix_attr() {
  local path="$1" mode="$2" owner="${3:-root:root}"
  [ -e "$path" ] || return 0
  [ -L "$path" ] && return 0
  local cur_mode cur_owner
  cur_mode=$(stat -c '%a' "$path")
  cur_owner=$(stat -c '%U:%G' "$path")
  if [ "$cur_mode" = "$mode" ] && [ "$cur_owner" = "$owner" ]; then
    return 0
  fi
  log "deviation: $path  $cur_owner $cur_mode  ->  $owner $mode"
  do_fix chown "$owner" "$path"
  do_fix chmod "$mode"  "$path"
  return 0
}

# Recursive chown. Applies only if any file inside differs.
fix_owner_recursive() {
  local dir="$1" owner="$2"
  [ -d "$dir" ] || return 0
  local bad
  bad=$(find "$dir" \( ! -user "${owner%%:*}" -o ! -group "${owner##*:}" \) 2>/dev/null | head -1)
  if [ -n "$bad" ]; then
    do_fix chown -R "$owner" "$dir"
  fi
  return 0
}

# =============================================================================
#  0.  Standard directory modes
# =============================================================================
#
# Top-level directories are 0755. Individual files and subdirectories
# carry the restrictive modes; the directories themselves must be
# traversable by every service account.
#
# /etc is the critical case: daemons running as non-root (mongodb,
# tor, php-fpm) need to reach their config files under /etc, and the
# kernel refuses path resolution if the directory blocks traversal.
# Package extraction with a restrictive umask can leave /etc at 0750;
# this section corrects it.

log "=== standard directory modes ==="

fix_attr /etc       755 root:root
fix_attr /var       755 root:root
fix_attr /var/log   755 root:root
fix_attr /var/run   755 root:root
fix_attr /var/lib   755 root:root
fix_attr /usr       755 root:root
fix_attr /usr/local 755 root:root
fix_attr /home      755 root:root

# =============================================================================
#  1.  /etc credential files
# =============================================================================
#
# Match what the distribution ships:
#   /etc/shadow, /etc/shadow-      root:root   600
#   /etc/gshadow, /etc/gshadow-    root:shadow 640

log "=== /etc credential files ==="

fix_attr /etc/passwd     644 root:root
fix_attr /etc/group      644 root:root
fix_attr /etc/shadow     600 root:root
fix_attr /etc/shadow-    600 root:root
fix_attr /etc/gshadow    600 root:root
fix_attr /etc/gshadow-   600 root:root
fix_attr /etc/shells     644 root:root
fix_attr /etc/login.defs 644 root:root

fix_attr /etc/sudoers 440 root:root
if [ -d /etc/sudoers.d ]; then
  fix_attr /etc/sudoers.d 750 root:root
  find /etc/sudoers.d -type f -exec chmod 440 {} \; 2>/dev/null || true
fi

# =============================================================================
#  2.  /etc/ssl/private
# =============================================================================

if [ -d /etc/ssl/private ]; then
  fix_attr /etc/ssl/private 700 root:root
fi

# =============================================================================
#  3.  SSH
# =============================================================================

log "=== SSH ==="

if [ -d /etc/ssh ]; then
  fix_attr /etc/ssh 700 root:root
  fix_attr /etc/ssh/sshd_config 600 root:root
  if [ -d /etc/ssh/sshd_config.d ]; then
    fix_attr /etc/ssh/sshd_config.d 750 root:root
  fi
  for k in /etc/ssh/ssh_host_*_key; do
    [ -f "$k" ] || continue
    fix_attr "$k" 600 root:root
  done
  for k in /etc/ssh/ssh_host_*_key.pub; do
    [ -f "$k" ] || continue
    fix_attr "$k" 644 root:root
  done
  [ -f /etc/ssh/moduli ] && fix_attr /etc/ssh/moduli 600 root:root
fi

# =============================================================================
#  4.  /boot
# =============================================================================

log "=== /boot ==="

for f in /boot/vmlinuz* /boot/System.map* /boot/config*; do
  [ -f "$f" ] || continue
  [ -L "$f" ] && continue
  fix_attr "$f" 640 root:root
done

fix_attr /boot/initrd.gz 600 root:root
fix_attr /boot/boot.0800 600 root:root
fix_attr /boot/map       600 root:root

# =============================================================================
#  5.  Logs
# =============================================================================

log "=== logs ==="

for f in /var/log/messages /var/log/syslog /var/log/secure \
         /var/log/auth.log /var/log/cron /var/log/debug \
         /var/log/maillog; do
  [ -f "$f" ] || continue
  fix_attr "$f" 640 root:root
done

if [ -f /var/log/wtmp ]; then
  fix_attr /var/log/wtmp 640 root:root
fi

# =============================================================================
#  6.  Kernel / modprobe / sysctl configs
# =============================================================================

log "=== kernel config ==="

if [ -d /etc/modprobe.d ]; then
  if [ "$DRY" = "1" ]; then
    log "WOULD: normalize modes on /etc/modprobe.d/*"
  else
    find /etc/modprobe.d -type f -exec chmod 644 {} \; 2>/dev/null || true
  fi
fi
if [ -d /etc/sysctl.d ]; then
  if [ "$DRY" = "1" ]; then
    log "WOULD: normalize modes on /etc/sysctl.d/*"
  else
    find /etc/sysctl.d -type f -exec chmod 644 {} \; 2>/dev/null || true
  fi
fi
fix_attr /etc/sysctl.conf 644 root:root

# =============================================================================
#  7.  Tor / MariaDB / Networking configs
# =============================================================================
#
# The tor daemon runs initially as root and creates
# /var/log/tor/notices.log as root:root. Subsequent starts (as the
# tor user, after privilege drop) cannot reopen it, and tor fails
# with "Couldn't open file for 'Log notice file ...': Permission
# denied". Recursive chown to tor:tor fixes it.

log "=== tor / mariadb ==="

if id tor >/dev/null 2>&1; then
  for d in /var/lib/tor /var/log/tor /var/run/tor; do
    [ -d "$d" ] || mkdir -p "$d" 2>/dev/null || true
  done

  fix_attr /etc/tor/torrc 644 root:root
  fix_attr /var/lib/tor  700 tor:tor
  fix_attr /var/log/tor  750 tor:tor
  fix_attr /var/run/tor  750 tor:tor

  fix_owner_recursive /var/lib/tor tor:tor
  fix_owner_recursive /var/log/tor tor:tor
  fix_owner_recursive /var/run/tor tor:tor
else
  warn "tor user missing; skipping tor state fixes"
fi

if [[ "$ISO_PROFILE" != "edge" ]]; then
fix_attr /etc/my.cnf      644 root:root
fix_attr /etc/my.cnf.d    755 root:root
fix_attr /var/lib/mysql   750 mysql:mysql
fi

if [ -d /etc/amos ]; then
  fix_attr /etc/amos 700 root:root
  fix_attr /etc/amos/gpg 700 root:root
  fix_attr /etc/amos/post-install.d 700 root:root
  fix_attr /etc/amos/post-install.d 700 root:root
  fix_attr /etc/amos/mirrors 600 root:root
  for f in /etc/amos/*; do
      [ -f "$f" ] && fix_attr "$f" 600 root:root
  done
  for f in /etc/amos/post-install.d/*.sh; do
      [ -f "$f" ] && fix_attr "$f" 700 root:root
  done
  for f in /etc/amos/gpg/*; do
      [ -f "$f" ] && fix_attr "$f" 600 root:root
  done
fi
# =============================================================================
#  8.  IMA certificate
# =============================================================================
#
# The IMA public certificate is staged into the target by amos package
# The kernel reads it at boot when
# CONFIG_IMA_LOAD_X509=y is set, loading the cert into the .ima
# trusted keyring. Every file with a security.ima xattr is then
# verified against it.
#
# Ownership from the repo is whatever the build user had. Normalise
# to root:root, mode 444. The kernel reads it as root; nothing else
# needs to write it. 444 rather than 400 so an admin can inspect it
# to confirm the loaded cert matches the expected one.

log "=== IMA certificate ==="

IMA_CERT=/etc/keys/x509_ima.der
if [ -f "$IMA_CERT" ]; then
    fix_attr /etc/keys        755 root:root
    fix_attr "$IMA_CERT"      444 root:root

    if command -v openssl >/dev/null 2>&1; then
        if openssl x509 -in "$IMA_CERT" -inform DER -noout >/dev/null 2>&1; then
            subj=$(openssl x509 -in "$IMA_CERT" -inform DER -noout -subject \
                   2>/dev/null | sed 's/^subject=//')
            log "cert parses OK: $subj"
        else
            warn "$IMA_CERT does not parse as DER X.509"
        fi
    fi
else
    warn "no IMA cert at $IMA_CERT; IMA appraisal will not work"
fi

[ -f /etc/ld.so.cache ] && fix_attr /etc/ld.so.cache 644 root:root

# =============================================================================
#  9.  php-fpm service account + config
# =============================================================================
#

log "=== php-fpm service account ==="

if ! id php-fpm >/dev/null 2>&1; then
  log "creating php-fpm user"
  do_fix useradd -r -d /var/lib/php-fpm -s /sbin/nologin php-fpm
else
  log "php-fpm user exists"
fi

if id php-fpm >/dev/null 2>&1; then
  mkdir -p /var/lib/php-fpm/session 2>/dev/null || true
  mkdir -p /var/log/php-fpm 2>/dev/null || true

  fix_attr /var/lib/php-fpm           750 php-fpm:php-fpm
  fix_attr /var/lib/php-fpm/session   700 php-fpm:php-fpm
  fix_attr /var/log/php-fpm           750 php-fpm:php-fpm
  fix_owner_recursive /var/lib/php-fpm php-fpm:php-fpm
  fix_owner_recursive /var/log/php-fpm php-fpm:php-fpm
fi

log "=== php-fpm pool config ==="

WWW=/etc/php-fpm.d/www.conf
if [ -f "$WWW" ]; then
  cur_user=$(awk -F' = ' '/^user = /{print $2; exit}' "$WWW")
  cur_group=$(awk -F' = ' '/^group = /{print $2; exit}' "$WWW")

  if [ "$cur_user" != "php-fpm" ]; then
    log "www.conf: user $cur_user -> php-fpm"
    if [ "$DRY" = "0" ]; then
      sed -i 's/^user = .*/user = php-fpm/' "$WWW"
    fi
  else
    log "www.conf: user already php-fpm"
  fi

  if [ "$cur_group" != "php-fpm" ]; then
    log "www.conf: group $cur_group -> php-fpm"
    if [ "$DRY" = "0" ]; then
      sed -i 's/^group = .*/group = php-fpm/' "$WWW"
    fi
  else
    log "www.conf: group already php-fpm"
  fi

  cur_listen=$(awk -F' = ' '/^listen = /{print $2; exit}' "$WWW")
  if [ "$cur_listen" != "10.200.2.1:9000" ]; then
    warn "www.conf: listen = $cur_listen (expected 10.200.2.1:9000)"
  fi
else
  warn "$WWW missing"
fi

log "=== rc.php-fpm ==="

RCPHP=/etc/rc.d/rc.php-fpm
if [ -f "$RCPHP" ]; then
  if [ ! -x "$RCPHP" ]; then
    do_fix chmod 755 "$RCPHP"
  else
    log "rc.php-fpm already executable"
  fi
else
  warn "$RCPHP missing"
fi

# =============================================================================
#  10.  Home directories
# =============================================================================

log "=== home directories ==="

fix_attr /root 700 root:root

for home in /home/*; do
  [ -d "$home" ] || continue
  owner=$(stat -c '%U' "$home")
  gname=$(stat -c '%G' "$home")
  uid=$(stat -c '%u' "$home")

  if [ "$uid" -lt 1000 ] || [ "$owner" = "root" ]; then
    warn "unusual home directory: $home  ($owner:$gname uid=$uid)"
    continue
  fi

  fix_attr "$home" 750 "$owner:$gname"

  for f in .ssh .gnupg; do
    [ -d "$home/$f" ] && fix_attr "$home/$f" 700 "$owner:$gname"
  done
  for f in .ssh/authorized_keys .ssh/id_rsa .ssh/id_ed25519 \
           .ssh/id_ecdsa .bash_history .netrc .pgpass; do
    [ -f "$home/$f" ] && fix_attr "$home/$f" 600 "$owner:$gname"
  done

done

# =============================================================================
#  11.  login.defs policy -- report always, change only when opted in
# =============================================================================

log "=== login.defs (policy) ==="

LD=/etc/login.defs
if [ -f "$LD" ]; then
  report_ld() {
    local key="$1" want="$2" cur
    cur=$(awk -v k="$key" '$1==k {print $2; exit}' "$LD")
    if [ -z "$cur" ]; then
      warn "login.defs: $key not set (recommend: $want)"
    elif [ "$cur" != "$want" ]; then
      warn "login.defs: $key = $cur (recommend: $want)"
    else
      log "login.defs: $key = $cur"
    fi
  }

  report_ld UMASK          027
  report_ld PASS_MAX_DAYS  365
  report_ld PASS_MIN_DAYS  1
  report_ld PASS_WARN_AGE  7
  report_ld ENCRYPT_METHOD SHA512

  if awk '$1=="HOME_MODE"{found=1; exit} END{exit !found}' "$LD"; then
    log "login.defs: HOME_MODE = $(awk '$1=="HOME_MODE"{print $2; exit}' "$LD")"
  else
    warn "login.defs: HOME_MODE not set (recommend: 0750 for new accounts)"
  fi

  if [ "$HARDEN_ACCOUNT_DEFAULTS" = "yes" ]; then
    if [ "$DRY" = "1" ]; then
      log "HARDEN_ACCOUNT_DEFAULTS=yes -- would apply login.defs changes"
    else
      log "HARDEN_ACCOUNT_DEFAULTS=yes -- applying login.defs changes"
    fi

    set_ld() {
      local key="$1" val="$2"
      if grep -qE "^[[:space:]]*${key}[[:space:]]" "$LD"; then
        if ! grep -qE "^[[:space:]]*${key}[[:space:]]+${val}([[:space:]]|$)" "$LD"; then
          if [ "$DRY" = "1" ]; then
            log "WOULD: login.defs: $key -> $val"
          elif sed -i -E "s|^[[:space:]]*${key}[[:space:]].*|${key}\t${val}|" "$LD"; then
            log "login.defs: $key -> $val"
          else
            warn "login.defs: failed to update $key"
          fi
        fi
      else
        if [ "$DRY" = "1" ]; then
          log "WOULD: login.defs: add $key $val"
        elif printf '%s\t%s\n' "$key" "$val" >> "$LD"; then
          log "login.defs: added $key $val"
        else
          warn "login.defs: failed to add $key"
        fi
      fi
    }

    set_ld UMASK          027
    set_ld PASS_MAX_DAYS  365
    set_ld PASS_MIN_DAYS  1
    set_ld PASS_WARN_AGE  7
    set_ld ENCRYPT_METHOD SHA512

    if ! awk '$1=="HOME_MODE"{found=1; exit} END{exit !found}' "$LD"; then
      if [ "$DRY" = "1" ]; then
        log "WOULD: login.defs: add HOME_MODE 0750"
      elif printf 'HOME_MODE\t0750\n' >> "$LD"; then
        log "login.defs: added HOME_MODE 0750"
      else
        warn "login.defs: failed to add HOME_MODE"
      fi
    fi
  else
    log "HARDEN_ACCOUNT_DEFAULTS=no; login.defs left unchanged"
  fi
fi

# =============================================================================
#  12.  Setuid / setgid inventory -- report only
# =============================================================================

log "=== setuid / setgid inventory ==="

SUID_BASELINE="
/bin/mount
/bin/ping
/bin/su
/bin/umount
/sbin/unix_chkpwd
/usr/bin/chage
/usr/bin/chfn
/usr/bin/chsh
/usr/bin/crontab
/usr/bin/expiry
/usr/bin/fdmount
/usr/bin/fusermount3
/usr/bin/gpasswd
/usr/bin/newgidmap
/usr/bin/newgrp
/usr/bin/newuidmap
/usr/bin/passwd
/usr/bin/sudo
/usr/bin/wall
/usr/bin/write
/usr/lib64/mysql/plugin/auth_pam_tool_dir/auth_pam_tool
/usr/libexec/ssh-keysign
"

is_in_baseline() {
  printf '%s\n' "$SUID_BASELINE" | grep -qx "$1"
}

find / -xdev -type f \( -perm -4000 -o -perm -2000 \) 2>/dev/null \
  | sort \
  | while read -r f; do
      perms=$(stat -c '%a' "$f")
      owner=$(stat -c '%U:%G' "$f")
      if is_in_baseline "$f"; then
        log "  ok        $perms $owner $f"
      else
        warn "UNEXPECTED  $perms $owner $f"
      fi
    done

# =============================================================================
#  13.  World-writable files outside /tmp, /home, and known sticky dirs
# =============================================================================
#
# Sticky-bit directories (/tmp, /var/tmp, /var/lock, /var/spool/mail,
# /dev/shm) are world-writable by design. Their sticky bit prevents
# deletion of other users' entries. Files inside them are not
# world-writable without sticky protection, so the file-level check
# skips those trees entirely.

log "=== world-writable files outside /tmp and /home ==="

find / -xdev -type f -perm -0002 \
     ! -path '/tmp/*' \
     ! -path '/var/tmp/*' \
     ! -path '/dev/shm/*' \
     ! -path '/run/*' \
     ! -path '/proc/*' \
     ! -path '/sys/*' \
     ! -path '/home/*' \
     2>/dev/null | while read -r f; do
  warn "world-writable file: $(stat -c '%U:%G %a' "$f") $f"
done

find / -xdev -type d -perm -0002 \
     ! -path '/tmp' \
     ! -path '/tmp/.ICE-unix' \
     ! -path '/tmp/.X11-unix' \
     ! -path '/var/tmp' \
     ! -path '/var/lock' \
     ! -path '/var/spool/mail' \
     ! -path '/dev/shm' \
     ! -path '/run/*' \
     ! -path '/proc/*' \
     ! -path '/sys/*' \
     ! -path '/home/*' \
     2>/dev/null | while read -r d; do
  warn "world-writable dir:  $(stat -c '%U:%G %a' "$d") $d"
done

# =============================================================================
#  14.  cron / at access
# =============================================================================

log "=== cron / at access ==="

if [ ! -f /etc/cron.allow ] && [ ! -f /etc/cron.deny ]; then
  warn "no /etc/cron.allow or /etc/cron.deny: any user can install cron jobs"
  warn "  to restrict to root only: create /etc/cron.allow containing 'root'"
else
  [ -f /etc/cron.allow ] && fix_attr /etc/cron.allow 640 root:root
  [ -f /etc/cron.deny  ] && fix_attr /etc/cron.deny  640 root:root
fi

fix_attr /etc/crontab 644 root:root
fix_attr /etc/cron.d 755 root:root
fix_attr /etc/cron.daily 755 root:root
fix_attr /etc/cron.hourly 755 root:root
fix_attr /etc/cron.weekly 755 root:root
fix_attr /etc/cron.monthly 755 root:root
if [ -d /var/spool/cron ]; then
  fix_attr /var/spool/cron 700 root:root
  fix_attr /var/spool/cron/crontabs 700 root:root
fi

# =============================================================================
#  15.  AppArmor
# =============================================================================

if [ -d /etc/apparmor.d ]; then
  fix_attr /etc/apparmor.d 755 root:root
  find /etc/apparmor.d -type f -exec chmod 644 {} \; 2>/dev/null || true
  find /etc/apparmor.d -type d -exec chmod 755 {} \; 2>/dev/null || true
fi


# =============================================================================
#  16.  Annode cgroup and directories (owned by netmode)
# =============================================================================

log "=== annode cgroup directories ==="

if [ -d /sys/fs/cgroup/annode ]; then
  cur=$(stat -c '%U:%G' /sys/fs/cgroup/annode)
  if [ "$cur" != "annode:annode" ]; then
    do_fix chown annode:annode /sys/fs/cgroup/annode
  fi
  if [ -d /sys/fs/cgroup/annode/tor ]; then
    cur=$(stat -c '%U:%G' /sys/fs/cgroup/annode/tor)
    if [ "$cur" != "annode:annode" ]; then
      do_fix chown annode:annode /sys/fs/cgroup/annode/tor
    fi
  fi
fi

  if [ -f "/home/annode/annode/anne-node.jar" ]; then
    fix_attr "/home/annode/annode/anne-node.jar" 640 "annode:annode"
    for d in a2a_cache a2a_localonly a2a_neurons amail tor-data; do
      [ -d "/home/annode/annode/$d" ] && fix_attr "/home/annode/annode/$d" 700 "annode:annode"
    done
  fi

find /home/annode/annode/html -type f -exec chmod 644 {} \; 2>/dev/null || true
find /home/annode/annode/conf -type f -exec chmod 644 {} \; 2>/dev/null || true
find /home/annode/annode -type d -exec chmod 755 {} \; 2>/dev/null || true

# =============================================================================
#  17.  Known doinst.sh quirks
# =============================================================================
# --- Fix ownership for files whose doinst.sh failed ---
# Packages like aaa_base and etc run doinst.sh before the shadow
# package has populated /etc/group with mail, utmp, and shadow.
log "Repairing ownership for mail, utmp, and shadow files..."

# Run directly, DO NOT use chroot here (we are already in the target)
[ -d /var/mail ] && chown -R root:mail /var/mail 2>/dev/null || true
[ -d /var/spool/mail ] && chown -R root:mail /var/spool/mail 2>/dev/null || true
[ -f /var/run/utmp ] && chown root:utmp /var/run/utmp 2>/dev/null || true
[ -f /var/log/wtmp ] && chown root:utmp /var/log/wtmp 2>/dev/null || true
[ -f /var/log/lastlog ] && chown root:utmp /var/log/lastlog 2>/dev/null || true
[ -f /var/log/btmp ] && chown root:utmp /var/log/btmp 2>/dev/null || true
[ -f /etc/shadow ] && chown root:root /etc/shadow 2>/dev/null || true
[ -f /etc/gshadow ] && chown root:root /etc/gshadow 2>/dev/null || true

log "Ownership repair complete."


# =============================================================================
#  18.  Edge package stripping (respects edge-keep.conf)
# =============================================================================
if [[ "$ISO_PROFILE" = "edge" ]] && [ "$DO_STRIP" -eq 1 ]; then

    log "=== Stripping Edge bloat ==="

    # --- Phase 1: Prune keep-list ---
    if [ -f /etc/amos/edge-keep.conf ] && [ "$DRY" = "0" ]; then
        tmp_keep=$(mktemp)
        while read -r p; do
            [ -z "$p" ] && continue
            # compgen -G is the safe way to check if a glob matches anything
            if compgen -G "/var/log/packages/${p}-[0-9]*" >/dev/null; then
                echo "$p" >> "$tmp_keep"
            else
                log "  pruning $p from edge-keep.conf (not installed)"
            fi
        done < /etc/amos/edge-keep.conf
        mv "$tmp_keep" /etc/amos/edge-keep.conf
        chmod 600 /etc/amos/edge-keep.conf
    fi
    
    # --- Phase 2: Strip files ---
    # Format: <package> <space-separated list of files/dirs>
    EDGE_STRIP_MANIFEST="
binutils  /usr/bin/ar /usr/bin/ranlib /usr/bin/windres /usr/bin/windmc /usr/bin/dlltool /usr/bin/lto-dump
elfutils  /usr/bin/eu-* /usr/lib64/libdw.so*
gcc       /usr/bin/gcc /usr/bin/g++ /usr/bin/cpp /usr/bin/cc /usr/libexec/gcc
plzip     /usr/bin/plzip /usr/bin/lzip /usr/bin/pzstd
icu4c     /usr/bin/pkgdata /usr/bin/makeconv /usr/bin/gendict /usr/bin/genbrk /usr/bin/gencfu /usr/bin/uconv /usr/bin/genrb /usr/bin/icuexportdata /usr/bin/derb /usr/bin/icuinfo /usr/bin/gencnval /usr/sbin/escapesrc /usr/sbin/icupkg /usr/sbin/genccode /usr/sbin/gensprep /usr/sbin/gencmn /usr/sbin/gennorm2 /usr/lib64/libicutu.so* /usr/lib64/libicuio.so* /usr/lib64/libicutest.so*
gnutls    /usr/bin/gnutls-cli /usr/bin/gnutls-serv /usr/bin/danetool /usr/lib64/libgnutls-dane.so* /usr/lib64/libgnutlsxx.so*
sqlite    /usr/bin/sqlite3 /usr/bin/sqlite3_rsync /usr/bin/dbhash /usr/bin/index_usage /usr/bin/sqldiff /usr/bin/dbdump
perl      /usr/lib64/perl5/vendor_perl/auto/DBD/mysql /usr/lib64/perl5/vendor_perl/auto/XML
"

    # We pipe into a while loop, which runs in a subshell. 
    # This is fine because we are just logging and deleting.
    echo "$EDGE_STRIP_MANIFEST" | while read -r pkg files; do
        [ -z "$pkg" ] && continue
        
        # Check if package is in the keep list (exact, fixed string match)
        if [ -f /etc/amos/edge-keep.conf ] && grep -qxF "$pkg" /etc/amos/edge-keep.conf; then
            log "  keeping $pkg (found in edge-keep.conf)"
            continue
        fi

        # Word-split the files list (this intentionally triggers shell globbing)
        for f in $files; do
            if [ -e "$f" ]; then
                if [ "$DRY" = "1" ]; then
                    log "  WOULD strip: $f"
                else
                    rm -rf "$f"
                fi
            fi
        done
    done

    log "=== Edge stripping complete ==="
fi

# =============================================================================
#  19. Isolate boot from userspace
# =============================================================================

chmod -R 0700 "/etc/rc.d"
chmod 0600 "/etc/rc.d/rc.inet1.conf"
if [[ "$ISO_PROFILE" != "edge" ]]; then
  mkdir -p "/etc/amos/rc.local.d"
  chmod 0700 "/etc/amos/rc.local.d"
  #comes from util-linux, handles legacy hardware. 
  # Hardware that supports plug-and-play, the kernel typically detects and configures the serial ports automatically
  rm -f /etc/rc.d/rc.serial
  # netmode already handles this
  rm -f /etc/rc.d/rc.ip_forward
fi
# =============================================================================
#  Done
# =============================================================================

log "=== complete (mode=$MODE, HARDEN_ACCOUNT_DEFAULTS=$HARDEN_ACCOUNT_DEFAULTS) ==="

if [ "$DRY" = "1" ]; then
  log "no changes applied; re-run with --apply to fix"
fi

exit 0
