#!/usr/bin/env bash
# This is a Calamares chroot job, never a standalone disk installer.
set -euo pipefail
[[ ${1:-} == --calamares-target && $EUID == 0 ]] || {
    echo 'This helper is only for the Calamares target chroot.' >&2; exit 1;
}
# mount.conf mounts proc in the target. PID 1 remains the live system's init.
# Refuse to modify the live root (or any environment without this proof).
[[ -d /proc/1/root ]] || { echo 'No live-root identity available.' >&2; exit 1; }
[[ $(stat -Lc '%d:%i' /) != "$(stat -Lc '%d:%i' /proc/1/root/.)" ]] || {
    echo 'Refusing to run target cleanup on the live root.' >&2; exit 1;
}
[[ -f /usr/lib/meowven/live-setup && -f /etc/arch-release ]] || {
    echo 'The target is not an unpacked Meowven live image.' >&2; exit 1;
}

systemctl disable meowven-live-setup.service 2>/dev/null || true
rm -f -- /etc/sddm.conf.d/99-meowven-live.conf /etc/sudoers.d/99-meowven-live
rm -f -- /usr/lib/systemd/system/meowven-live-setup.service
rm -f -- /etc/systemd/system/meowven-live-setup.service
rm -f -- /usr/lib/meowven/live-setup
rm -f -- /etc/systemd/system/getty@tty1.service.d/autologin.conf
rm -f -- /etc/systemd/system/multi-user.target.wants/meowven-live-setup.service
rm -f -- /etc/systemd/system/graphical.target.wants/meowven-live-setup.service
if getent passwd meowven >/dev/null; then
    userdel --remove meowven
fi
# The normal users module runs next; it creates the user's chosen account.
passwd --lock root

# archiso builds its own initramfs. The installed system needs a standard kernel
# and preset so mkinitcpio and future Arch kernel upgrades work normally.
mapfile -t kernels < <(pacman -Qlq linux | sed -n '\#^/usr/lib/modules/[^/]\+/vmlinuz$#p')
[[ ${#kernels[@]} == 1 && -s ${kernels[0]} ]] || {
    echo 'Expected exactly one packaged linux kernel.' >&2; exit 1;
}
install -Dm644 "${kernels[0]}" /boot/vmlinuz-linux
rm -f -- /etc/mkinitcpio.conf.d/archiso.conf
rm -f -- /etc/mkinitcpio.conf.d/00-archiso.conf
rm -f -- /etc/mkinitcpio.d/linux.preset
cat > /etc/mkinitcpio.d/linux.preset <<'PRESET'
ALL_kver='/boot/vmlinuz-linux'
PRESETS=('default' 'fallback')
default_image='/boot/initramfs-linux.img'
fallback_image='/boot/initramfs-linux-fallback.img'
fallback_options='-S autodetect'
PRESET
chmod 644 /etc/mkinitcpio.d/linux.preset

# Remove the inherited initramfs and installer desktop shortcut from the target.
rm -f -- /boot/initramfs-linux.img /boot/initramfs-linux-fallback.img
rm -f -- /etc/skel/Desktop/meowven-install.desktop
rm -f -- /usr/share/xsessions/meowven-installer-x11.desktop
# Archiso's mirror/keyring initialization units must not start on the installed OS.
systemctl disable pacman-init.service choose-mirror.service 2>/dev/null || true
