#!/bin/bash
# amos-geninitrd
#
# Regenerate /boot/initrd.gz with the AM·OS IMA policy, cert, and
# pre-switch_root hook injected. Follows geninitrd(8) conventions:
# reads $KERNEL from the environment, extracts the version from the
# kernel image itself, no version argument required.
#
# Called by install.sh at install time (with KERNEL=... in env) and
# by geninitrd via GENINITRD_OVERRIDE_SCRIPT at kernel upgrade time
# (doinst.sh already sets KERNEL).
#
# Config: /etc/default/amos-geninitrd (optional).
#   AMOS_EXTRA_MODS  extra modules to append to the -m argument
#   AMOS_OUT         output path (default: /boot/initrd.gz)

set -eu

# --- Determine which kernel to build for. ---
# Priority: $1 > $KERNEL > newest under /lib/modules.
KERNEL="${1:-${KERNEL:-}}"

if [ -z "$KERNEL" ]; then
  newest_mod=$(ls -1 /lib/modules 2>/dev/null | sort -V | tail -n1)
  [ -n "$newest_mod" ] || { echo "no kernel specified and no /lib/modules entries" >&2; exit 1; }
  for p in /boot/vmlinuz-"$newest_mod" /boot/vmlinuz; do
    [ -r "$p" ] && { KERNEL="$p"; break; }
  done
fi

[ -n "$KERNEL" ] && [ -r "$KERNEL" ] \
  || { echo "no readable kernel image (KERNEL='${KERNEL:-}', tried \$1, \$KERNEL, autodetect)" >&2; exit 1; }

KVER=$(strings "$KERNEL" | grep '([^ ]*@[^ ]*) #' | cut -f1 -d' ')
[ -n "$KVER" ] || { echo "$KERNEL is not a Linux kernel image" >&2; exit 1; }

log() { printf '[amos-geninitrd] %s\n' "$*"; }
die() { printf '[amos-geninitrd] ERROR: %s\n' "$*" >&2; exit 1; }

log "kernel image: $KERNEL"
log "kernel version: $KVER"

GEN=/usr/share/mkinitrd/mkinitrd_command_generator.sh
TREE=/boot/initrd-tree
IMA_CERT=/etc/keys/x509_ima.der
IMA_POLICY=/etc/ima/ima-policy
IMA_HOOK=/usr/local/share/amos/load-ima-policy.sh

[ -r /etc/default/amos-geninitrd ] && . /etc/default/amos-geninitrd

AMOS_EXTRA_MODS="${AMOS_EXTRA_MODS:-bochs:fbcon:drm:drm_kms_helper}"
AMOS_OUT="${AMOS_OUT:-/boot/initrd.gz}"

[ -x "$GEN" ]          || die "missing $GEN"
[ -f "$IMA_CERT" ]     || die "missing $IMA_CERT"
[ -f "$IMA_POLICY" ]   || die "missing $IMA_POLICY"
[ -f "$IMA_HOOK" ]     || die "missing $IMA_HOOK"

# --- 1. Ask the stock generator for a baseline command. ---
gen_raw=$("$GEN" -k "$KVER" -a "-u -o $AMOS_OUT" 2>&1)
gen_cmd=$(printf '%s\n' "$gen_raw" | grep -E '^mkinitrd ' | head -n1)
[ -n "$gen_cmd" ] || die "generator produced no mkinitrd line"
log "generator: $gen_cmd"

# --- 2. Force a clean rebuild: strip -u, ensure -c is present. ---
gen_cmd=$(printf '%s' "$gen_cmd" | sed 's| -u | |g')
case "$gen_cmd" in
  *" -c "*) : ;;
  *)        gen_cmd=$(printf '%s' "$gen_cmd" | sed 's| mkinitrd | mkinitrd -c |') ;;
esac

# --- 3. Splice AM·OS extra modules into the -m argument. ---
if printf '%s' "$gen_cmd" | grep -q ' -m '; then
  gen_cmd=$(printf '%s' "$gen_cmd" | sed "s| -m \([^ ]*\)| -m \1:${AMOS_EXTRA_MODS}|")
else
  gen_cmd=$(printf '%s ' "$gen_cmd" | sed "s| -o | -m ${AMOS_EXTRA_MODS} -o |")
fi
log "spliced: $gen_cmd"

# --- 4. Build the tree. ---
log "building initrd tree"
$gen_cmd || die "mkinitrd (build) failed"

# --- 5. Inject IMA artifacts into the fresh tree. ---
log "injecting IMA artifacts"
install -D -m 0444 -o 0 -g 0 "$IMA_CERT"   "$TREE/etc/keys/x509_ima.der"
install -D -m 0600 -o 0 -g 0 "$IMA_POLICY" "$TREE/etc/ima/ima-policy"
install -D -m 0755 -o 0 -g 0 "$IMA_HOOK"   "$TREE/etc/initrd/load-ima-policy.sh"

# --- 6. Hook policy load into /init, before switch_root. ---
if [ -f "$TREE/init" ] && ! grep -q 'load-ima-policy' "$TREE/init"; then
  sed -i '/^exec switch_root/i . /etc/initrd/load-ima-policy.sh' "$TREE/init"
  log "hooked policy load into /init"
fi

# --- 5a. Inject fsck and its libraries into the initrd tree ---
log "injecting fsck binaries into initrd"
for bin in /sbin/fsck /sbin/e2fsck; do
  if [ -x "$bin" ]; then
    install -D -m 0755 "$bin" "$TREE$bin"
    # Copy shared libraries AND the dynamic linker (columns 1 and 3)
    ldd "$bin" 2>/dev/null | awk '{ if ($1 ~ /^\//) print $1; if ($3 ~ /^\//) print $3 }' | while read lib; do
      if [ -f "$lib" ]; then
        install -D -m 0755 "$lib" "$TREE$lib"
      fi
    done
  fi
done

# Add the missing symlink so the fsck wrapper can find it
ln -sf /sbin/e2fsck "$TREE/sbin/fsck.ext4"

# --- 5b. Inject fsck directly into /init via awk ---
log "injecting fsck logic directly into /init"
if [ -f "$TREE/init" ] && ! grep -q 'AMOS_FSCK' "$TREE/init"; then
  awk '
    /mount -o ro.*\$ROOTDEV \/mnt/ {
      print "# AMOS_FSCK: Automatic check and repair"
      print "if [ -x /sbin/e2fsck ]; then"
      print "  echo \"Checking root filesystem $ROOTDEV...\" > /dev/kmsg"
      print "  /sbin/e2fsck -fy \"$ROOTDEV\""
      print "  FSCK_RET=$?"
      print "  if [ $FSCK_RET -ge 2 ]; then"
      print "    echo \"AMOS: fsck failed. Dropping to shell.\" > /dev/kmsg"
      print "    /bin/sh"
      print "  fi"
      print "fi"
    }
    { print }
  ' "$TREE/init" > "$TREE/init.new" && mv "$TREE/init.new" "$TREE/init"
  chmod 755 "$TREE/init"
  
  # Safety check
  if ! grep -q 'AMOS_FSCK' "$TREE/init"; then
    die "Failed to inject fsck logic into /init"
  fi
  log "fsck logic injected successfully"
fi

# --- 6a. Silencing initrd module loading spam ---
if [ -f "$TREE/init" ]; then
  # 1. Silence the echo statement
  sed -i 's|echo "${INITRD}:  Loading kernel modules from initrd image:"|:|g' "$TREE/init"
  
  # 2. Silence the load_kernel_modules script execution
  sed -i 's|^\([[:space:]]*\)\. \./load_kernel_modules$|\1. ./load_kernel_modules >/dev/null 2>\&1|' "$TREE/init"
  
  # 3. Silence the fallback modprobe loop
  sed -i 's|^\([[:space:]]*\)/sbin/modprobe \$module$|\1/sbin/modprobe $module >/dev/null 2>\&1|' "$TREE/init"
  
  log "silenced initrd module loading output"
fi

# --- 7. Repack from the injected tree. ---
log "repacking initrd from $TREE"
mkinitrd -k "$KVER" -s "$TREE" -o "$AMOS_OUT" || die "mkinitrd (repack) failed"

[ -s "$AMOS_OUT" ] || die "$AMOS_OUT missing or empty after repack"

# --- 8. Combine microcode if present. ---
ucode=""
case "$(awk -F': ' '/^vendor_id/ {print $2; exit}' /proc/cpuinfo 2>/dev/null)" in
  GenuineIntel) [ -f /boot/intel-ucode.img ] && ucode=/boot/intel-ucode.img ;;
  AuthenticAMD) [ -f /boot/amd-ucode.img   ] && ucode=/boot/amd-ucode.img   ;;
esac
if [ -n "$ucode" ]; then
  tmp=$(mktemp "${AMOS_OUT}.XXXXXX")
  cat "$ucode" "$AMOS_OUT" > "$tmp" && mv "$tmp" "$AMOS_OUT"
  log "prepended $(basename "$ucode")"
fi

# --- 8b. Sync to the ESP on EFI systems. ---
# On EFI, elilo loads vmlinuz and initrd.gz from the ESP, not from
# /boot. If the ESP copies are stale, the next reboot brings up the
# previous kernel and previous initrd. Update both mirrors the
# installer uses.
if [ -d /sys/firmware/efi ] && [ -d /boot/efi ]; then
  for esp_dir in /boot/efi/EFI/AMOS /boot/efi/EFI/BOOT; do
    [ -d "$esp_dir" ] || continue

    # Kernel: /boot/vmlinuz-generic is a symlink to the new kernel.
    # Dereference it and copy the target.
    if [ -r /boot/vmlinuz-generic ]; then
      cp -fL /boot/vmlinuz-generic "$esp_dir/vmlinuz" \
        || die "failed to update $esp_dir/vmlinuz"
      log "synced $esp_dir/vmlinuz"
    fi

    # Initrd: copy the combined artifact (microcode + initrd).
    cp -f "$AMOS_OUT" "$esp_dir/initrd.gz" \
      || die "failed to update $esp_dir/initrd.gz"
    log "synced $esp_dir/initrd.gz"
  done

  # Best-effort: ask the firmware to refresh the boot entry.
  # Not fatal if it fails -- the existing entry still points at the
  # right path, only the underlying files changed.
  if command -v efibootmgr >/dev/null 2>&1; then
    efibootmgr >/dev/null 2>&1 || \
      log "efibootmgr could not read NVRAM (harmless)"
  fi
fi

# --- 8c. Refresh LILO on BIOS systems (upgrade path only). ---
# LILO embeds kernel/initrd sector numbers into the MBR at 'lilo' time;
# it does not read the files at boot. A kernel upgrade that leaves the
# MBR pointing at the old sectors will boot the old kernel or fail.
#
# SKIPPED when AMOS_INSTALL=1: install.sh calls this script BEFORE it
# writes /etc/lilo.conf. At that point the file on disk is the package
# sample, which has boot=/dev/sda — inside the install chroot, /dev/sda
# is bind-mounted from the live system, so a lilo run there would write
# the LIVE disk's MBR. install.sh runs lilo itself afterwards (in
# exec_bootloader_bios) with the correct config.
#
# On the upgrade path (called from doinst.sh on the live system),
# this is exactly the right moment and the right config.
if [ -z "${AMOS_INSTALL:-}" ] \
   && [ ! -d /sys/firmware/efi ] \
   && [ -f /etc/lilo.conf ] \
   && command -v lilo >/dev/null 2>&1; then
    log "refreshing LILO boot record"
    if lilo >/tmp/amos-lilo.log 2>&1; then
        log "lilo OK"
        rm -f /run/amos-lilo-failed
    else
        log "WARNING: lilo failed; machine may not boot the new kernel"
        log "         run 'lilo' manually before rebooting"
        cp /tmp/amos-lilo.log /run/amos-lilo-failed 2>/dev/null || true
        # Do not die: aborting would break the doinst.sh transaction.
    fi
fi

# --- 9. Tree is no longer needed. ---
rm -rf "$TREE"

log "done: $AMOS_OUT"