#!/bin/bash
# pagan-initramfs – przebudowa initramfs Pagan Linux (rolling: po aktualizacji jądra).
#
# Dla KAŻDEGO jądra (/boot/vmlinuz-<ver> + /usr/lib/modules/<ver>) buduje OSOBNY
# plik /boot/initramfs-<ver>.img i aktualizuje aliasy czytane przez
# /etc/grub.d/10_linux (initrd.img-<ver>, initramfs-<ver>.img). Wspólny plik
# initramfs był przyczyną stanu „nowe moduły na starym jądrze” po `pag upgrade`.
#
# Kolejność builderów: dracut → mkinitcpio → mkinitramfs → własny busybox+cpio.
# Opcjonalny argument: konkretna wersja jądra (np. 7.2.8-pagan).

[ "$(id -u)" = "0" ] || { echo "Uruchom jako root" >&2; exit 1; }

BOOT="${PAGAN_BOOT_DIR:-/boot}"
MODS="${PAGAN_MODULES_DIR:-/usr/lib/modules}"

# ── lista wersji jąder do przebudowy (argument albo wszystkie z /boot) ───────
_versions() {
    if [ "$#" -gt 0 ] && [ -n "${1:-}" ]; then printf '%s\n' "$1"; return 0; fi
    for k in "$BOOT"/vmlinuz-*; do
        [ -e "$k" ] || continue
        b="$(basename "$k")"; v="${b#vmlinuz-}"
        [ "$v" != "$b" ] || continue
        printf '%s\n' "$v"
    done | sort -V
}

# ── fallback: minimalny initramfs (busybox + cpio), bez modułów jądra ────────
# Moduły nie są potrzebne: jądro budowane przez Pagan ma dysk/FS/LUKS wbudowane
# (initramfs ma tylko zamontować root i zrobić switch_root).
_fallback_build() {
    local ver="$1" out="$2"
    echo "Fallback: busybox+cpio (initramfs dla $ver)..."
    local TMP; TMP="$(mktemp -d)" || return 1
    mkdir -p "$TMP"/bin "$TMP"/dev "$TMP"/proc "$TMP"/sys "$TMP"/run \
             "$TMP"/new_root "$TMP"/etc "$TMP"/usr/sbin "$TMP"/usr/lib "$TMP"/lib "$TMP"/lib64

    cat > "$TMP/init" <<'INITEOF'
#!/bin/sh
# Pagan Linux initramfs init (minimal: dysk + LUKS + deploymenty).
mount -t proc proc /proc 2>/dev/null
mount -t sysfs sysfs /sys 2>/dev/null
mount -t devtmpfs dev /dev 2>/dev/null || mount -t tmpfs dev /dev 2>/dev/null
mkdir -p /run /new_root /etc /usr/sbin /usr/bin /bin /sbin

ROOT_DEV=""
CRYPT_DEV_ARG=""
for arg in $(cat /proc/cmdline 2>/dev/null); do
    case "$arg" in
        root=*)        ROOT_DEV="${arg#root=}" ;;
        cryptdevice=*) CRYPT_DEV_ARG="${arg#cryptdevice=}" ;;
    esac
done
[ -n "$ROOT_DEV" ] || ROOT_DEV="/dev/sda1"

# ── root=UUID=/PARTUUID=/LABEL= → konkretne urządzenie ──────────────────────
# BusyBox `mount` NIE rozwiązuje UUID=/LABEL= (inaczej niż util-linux). Bez tego
# po przebudowie initramfs system wisiał na starcie („nie można zamontować roota”).
_blkid_get() {
    blkid "$1" 2>/dev/null | tr ' ' '\n' | grep "^$2=" | head -1 | cut -d= -f2- | tr -d '"'
}
_resolve_root() {
    local key="$1" val="$2" d
    for d in /dev/sd*[0-9] /dev/hd*[0-9] /dev/vd*[0-9] \
             /dev/nvme*n[0-9]*p[0-9]* /dev/mmcblk*p[0-9]* \
             /dev/dm-[0-9]* /dev/mapper/*; do
        [ -b "$d" ] || continue
        [ "$(_blkid_get "$d" "$key")" = "$val" ] && { printf '%s' "$d"; return 0; }
    done
    return 1
}
case "$ROOT_DEV" in
    UUID=*)     _r="$(_resolve_root UUID "${ROOT_DEV#UUID=}")"     && ROOT_DEV="$_r" ;;
    PARTUUID=*) _r="$(_resolve_root PARTUUID "${ROOT_DEV#PARTUUID=}")" && ROOT_DEV="$_r" ;;
    LABEL=*)    _r="$(_resolve_root LABEL "${ROOT_DEV#LABEL=}")"   && ROOT_DEV="$_r" ;;
esac

# ---- LUKS: odblokowanie roota (cryptdevice= lub wprost partycja LUKS) ----
unlock_luks() {
    local dev="$1" name="$2" pass
    [ -n "$name" ] || name="cryptroot"
    mkdir -p /dev/mapper
    mknod /dev/mapper/control c 10 236 2>/dev/null
    modprobe dm-crypt 2>/dev/null || true
    if ! command -v cryptsetup >/dev/null 2>&1; then
        echo "[pagan-init] ERROR: no cryptsetup in initramfs - cannot unlock $dev"
        return 1
    fi
    stty -echo 2>/dev/null
    printf "Password (LUKS %s): " "$dev"; read -r pass; stty echo 2>/dev/null; echo
    if ! printf '%s\n' "$pass" | cryptsetup open "$dev" "$name" 2>/dev/null; then
        pass=""; echo "[pagan-init] ERROR: failed to unlock $dev (wrong password?)"; return 1
    fi
    pass=""; echo "[pagan-init] Odblokowano /dev/mapper/$name"; return 0
}

if [ -n "$CRYPT_DEV_ARG" ]; then
    crypt_src="${CRYPT_DEV_ARG%%:*}"; crypt_name="${CRYPT_DEV_ARG#*:}"; crypt_name="${crypt_name%%:*}"
    crypt_dev=""
    case "$crypt_src" in
        UUID=*)
            want="${crypt_src#UUID=}"
            for d in /dev/sd*[0-9] /dev/hd*[0-9] /dev/vd*[0-9] /dev/nvme*n[0-9]*p[0-9]* /dev/mmcblk*p[0-9]*; do
                [ -b "$d" ] || continue
                [ "$(cryptsetup luksUUID "$d" 2>/dev/null)" = "$want" ] && { crypt_dev="$d"; break; }
            done ;;
        /dev/*) crypt_dev="$crypt_src" ;;
    esac
    if [ -n "$crypt_dev" ] && [ -b "$crypt_dev" ]; then
        if unlock_luks "$crypt_dev" "$crypt_name"; then ROOT_DEV="/dev/mapper/$crypt_name"
        else echo "[pagan-init] Rescue shell:"; exec /bin/sh; fi
    else
        echo "[pagan-init] BŁĄD: cryptdevice nie znaleziono ($crypt_src)"; exec /bin/sh
    fi
fi

i=0
while [ ! -e "$ROOT_DEV" ] && [ "$i" -lt 10 ]; do sleep 1; i=$((i+1)); done

# Fallback: root= wskazuje wprost na partycję LUKS. `cryptsetup isLuks` jest
# jednoznaczne (BusyBox `blkid -t` ignoruje filtr i zawsze zwraca 0).
if cryptsetup isLuks "$ROOT_DEV" 2>/dev/null; then
    echo "[pagan-init] Wykryto LUKS na root ($ROOT_DEV)"
    if unlock_luks "$ROOT_DEV" cryptroot; then ROOT_DEV="/dev/mapper/cryptroot"
    else echo "[pagan-init] Rescue shell:"; exec /bin/sh; fi
fi

mount -t auto -o rw "$ROOT_DEV" /new_root 2>/dev/null || {
    echo "[pagan-init] ERROR: cannot mount root ($ROOT_DEV)"; exec /bin/sh; }

# Deploymenty PAG (immutable OS)
ACTIVE="/new_root/.deployments/active"; DEP=""
if [ -L "$ACTIVE" ]; then
    DEP=$(readlink "$ACTIVE"); [ -n "$DEP" ] && DEP="/new_root/.deployments/$DEP"
elif [ -d "/new_root/.deployments" ]; then
    DEP=$(ls -1 /new_root/.deployments/ 2>/dev/null | grep -v active | sort -r | head -1)
    [ -n "$DEP" ] && DEP="/new_root/.deployments/$DEP"
fi
[ -n "$DEP" ] && [ -d "$DEP" ] && NEWROOT="$DEP" || NEWROOT="/new_root"

mount --move /proc "$NEWROOT/proc" 2>/dev/null
mount --move /sys "$NEWROOT/sys" 2>/dev/null
mount --move /dev "$NEWROOT/dev" 2>/dev/null
exec switch_root "$NEWROOT" /sbin/init
INITEOF
    chmod +x "$TMP/init"

    # busybox (statyczny) lub kopie binarek HOSTA
    BB=""
    for p in /usr/bin/busybox /bin/busybox; do [ -x "$p" ] && BB="$p" && break; done
    if [ -n "$BB" ]; then
        cp "$BB" "$TMP/bin/busybox"; chmod 755 "$TMP/bin/busybox"
        for c in sh mount umount ls cat echo sleep readlink mkdir switch_root cp rm ln grep \
                 poweroff reboot blkid mknod stty sed sort cut tr head vi; do
            ln -sf busybox "$TMP/bin/$c"
        done
    else
        for t in sh bash mount umount ls cat echo sleep readlink mkdir switch_root cp rm ln grep \
                 blkid mknod stty sed sort cut tr head; do
            s="$(command -v "$t" 2>/dev/null)" && [ -n "$s" ] && [ -f "$s" ] && cp "$s" "$TMP/bin/"
        done
    fi

    # cryptsetup + biblioteki (obsługa LUKS) – jeśli system go ma
    CS=""
    for p in /usr/sbin/cryptsetup /usr/bin/cryptsetup /sbin/cryptsetup; do [ -x "$p" ] && CS="$p" && break; done
    if [ -n "$CS" ]; then
        cp "$CS" "$TMP/usr/sbin/cryptsetup"; chmod 755 "$TMP/usr/sbin/cryptsetup"
        for lib in $(ldd "$CS" 2>/dev/null | awk '/=>/ {print $3} /^[[:space:]]*\// {print $1}'); do
            [ -f "$lib" ] || continue
            d="${lib#"${PAGAN_ROOT:-}"}"; d="${d#/}"; [ -n "$d" ] || continue
            mkdir -p "$TMP/${d%/*}"; cp -fL "$lib" "$TMP/$d" 2>/dev/null || true
        done
        # Domknięcie zależności PRZECHODNICH (jedno ldd pomija np. libcrypto.so.3).
        for _pass in 1 2 3; do
            for f in "$TMP"/usr/lib/*.so* "$TMP"/lib/*.so*; do
                [ -f "$f" ] || continue
                for lib in $(ldd "$f" 2>/dev/null | awk '/=>[[:space:]]*\// {print $3}'); do
                    [ -f "$lib" ] || continue
                    d="${lib#"${PAGAN_ROOT:-}"}"; d="${d#/}"; [ -n "$d" ] || continue
                    [ -e "$TMP/$d" ] && continue
                    mkdir -p "$TMP/${d%/*}"; cp -fL "$lib" "$TMP/$d" 2>/dev/null || true
                done
            done
        done
        loader="$(ldd "$CS" 2>/dev/null | awk '/ld-linux/ {print $1}')"
        if [ -n "$loader" ] && [ -f "$loader" ]; then
            mkdir -p "$TMP${loader%/*}"; cp -fL "$loader" "$TMP$loader"
        fi
    fi
    [ -f /etc/pagan-release ] && cp /etc/pagan-release "$TMP/etc/"

    ( cd "$TMP" && find . | cpio -oH newc 2>/dev/null | gzip ) > "$out" || { rm -rf "$TMP"; return 1; }
    rm -rf "$TMP"
    return 0
}

# ── zbuduj initramfs dla jednej wersji jądra do pliku $out ───────────────────
_build_one() {
    local ver="$1" out="$2"
    if [ ! -d "$MODS/$ver" ]; then
        echo "⚠  no modules for $ver ($MODS/$ver) - skipping"
        return 1
    fi
    if command -v dracut >/dev/null 2>&1; then
        dracut --force --kver "$ver" "$out" >/dev/null 2>&1 && return 0
    fi
    if command -v mkinitcpio >/dev/null 2>&1; then
        mkinitcpio -k "$ver" -g "$out" >/dev/null 2>&1 && return 0
    fi
    if command -v mkinitramfs >/dev/null 2>&1; then
        mkinitramfs -o "$out" -k "$ver" >/dev/null 2>&1 || mkinitramfs "$ver" >/dev/null 2>&1
        [ -s "$out" ] && return 0
    fi
    _fallback_build "$ver" "$out"
}

built_any=0
for ver in $(_versions "${1:-}"); do
    out="$BOOT/initramfs-$ver.img"
    [ -L "$out" ] && rm -f "$out"          # nie pisz „przez” stary symlink
    if _build_one "$ver" "$out"; then
        ln -sfn "initramfs-$ver.img" "$BOOT/initrd.img-$ver"
        built_any=1
        echo "✅ initramfs-$ver.img"
    else
        rm -f "$out"
    fi
done

if [ "$built_any" = "1" ]; then
    # UWAGA: /boot/vmlinuz-linux to ALIAS (symlink), nie wersja. Wcześniej
    # trafiał do sort -V i wygrywał („linux” > „7.2.11-pagan”), przez co
    # initramfs.img wskazywał na nieistniejący initramfs-linux.img, a wpis
    # GRUB-a dla vmlinuz-linux startował BEZ initramfs (panika na NVMe/LUKS).
    newest="$(for k in "$BOOT"/vmlinuz-*; do
                  [ -e "$k" ] || continue
                  [ -L "$k" ] && continue
                  b="${k##*/}"; v="${b#vmlinuz-}"
                  case "$v" in [0-9]*) printf '%s\n' "$v" ;; esac
              done | sort -V | tail -1)"
    if [ -n "$newest" ]; then
        ln -sfn "initramfs-$newest.img" "$BOOT/initramfs.img"
        # Aliasy, których szuka /etc/grub.d/10_linux dla wpisu vmlinuz-linux.
        if [ -e "$BOOT/vmlinuz-linux" ]; then
            [ -e "$BOOT/initramfs-linux.img" ] || [ -L "$BOOT/initramfs-linux.img" ] || \
                ln -sfn "initramfs.img" "$BOOT/initramfs-linux.img"
            [ -e "$BOOT/initrd.img-linux" ] || [ -L "$BOOT/initrd.img-linux" ] || \
                ln -sfn "initramfs.img" "$BOOT/initrd.img-linux"
        fi
    fi
    exit 0
fi
echo "❌ No initramfs built (no kernels in $BOOT?)" >&2
exit 1
