#!/bin/sh
# Runs only inside the live environment or Debian Installer. All persistent
# writes are confined to the identified marker volume on the boot USB.
set -eu
export LC_ALL=C
export PATH=/usr/sbin:/usr/bin:/sbin:/bin
umask 077
run=/run/newworld-usblog
volume=$run/volume
ram=$run/boot.log
sys=/sys
proc=/proc
dev=/dev
status=$run/status.json
now() { date -u '+%Y-%m-%dT%H:%M:%SZ'; }
first() { sed -n '1{s/[^A-Za-z0-9 ._()+@:-]/?/g;s/^ *//;s/ *$//;p;}' "$1" 2>/dev/null | head -c 100; }
write_ram() { printf '%s %s\n' "$(now)" "$*" >> "$ram"; }
relative=
reason=none
persistent=no
mode=install
case " $(cat "$proc/cmdline") " in
    *' newworld.debug=1 '*) mode=debug ;;
    *' newworld.autoinstall=1 '*) : ;;
    *) exit 2 ;;
esac
phase=prepare
percent=0
estimate=null
# This directory lives in the installer, not on a potential target system.
mkdir -p "$run"
[ ! -L "$run" ] && [ "$(ls -nd "$run" | awk '{print $3}')" = 0 ] || exit 1
chmod 755 "$run"
mkdir -p "$volume"
lock=$run/lock
tries=0
while ! mkdir "$lock" 2>/dev/null; do
    tries=$((tries+1)); [ "$tries" -le 6 ] || exit 1
    sleep 1
done
trap 'rmdir "$lock" 2>/dev/null || :' EXIT
trap 'exit 1' HUP INT TERM

status_write() {
    # All strings written into JSON originate from a fixed enum or a generated filename.
    tmp_status=$run/status.$$
    printf '{"state":"%s","mode":"%s","relative":"%s","reason":"%s","phase":"%s","percent":%s,"eta_seconds":%s}\n' \
        "$1" "$mode" "$relative" "$reason" "$phase" "$percent" "$estimate" > "$tmp_status"
    chmod 644 "$tmp_status"
    mv "$tmp_status" "$status"
}
persist_failed() {
    persistent=no
    relative=
    reason=$1
    printf '%s\n' "$reason" > "$run/reason"
    status_write unavailable
}
mounted_here() {
    [ -s "$run/devnum" ] && awk -v p="$volume" -v n="$(cat "$run/devnum")" '
        $5==p && $3==n {yes=1} END{exit !yes}' "$proc/self/mountinfo"
}
append() {
    write_ram "$@"
    if [ "$persistent" = yes ]; then
        if ! mounted_here || ! printf '%s %s\n' "$(now)" "$*" >> "$volume/$relative"; then
            persist_failed write_failed
        fi
    fi
}
# Return a specific mounting reason to the nonprivileged presentation UI.
select_volume() {
    nums=$(awk '$5=="/cdrom" || $5=="/run/live/medium" || $5=="/lib/live/mount/medium" || $5=="/run/initramfs/live" {print $3}' "$proc/self/mountinfo" | sort -u)
    [ -n "$nums" ] || { reason=no_medium; return 1; }
    parent=
    for num in $nums; do
        device_path=$(readlink -f "$sys/dev/block/$num") || { reason=no_medium; return 1; }
        [ -e "$device_path/dev" ] || { reason=no_medium; return 1; }
        if [ -f "$device_path/partition" ]; then device_path=${device_path%/*}; fi
        [ -z "$parent" ] || [ "$parent" = "$device_path" ] || { reason=no_medium; return 1; }
        parent=$device_path
    done
    # Decline stacked, optical and internal backing, including multiboot
    # setups where the physical installer stick cannot be positively identified.
    usb=no; ancestor=$parent
    while [ "$ancestor" != / ] && [ -n "$ancestor" ]; do
        if [ -L "$ancestor/subsystem" ] && [ "$(basename "$(readlink -f "$ancestor/subsystem")")" = usb ]; then usb=yes; break; fi
        ancestor=${ancestor%/*}
    done
    [ "$usb" = yes ] || { reason=no_usb_medium; return 1; }
    [ "$(cat "$parent/ro")" = 0 ] || { reason=read_only; return 1; }
    found=
    for child in "$parent"/*; do
        [ -f "$child/partition" ] || continue
        device=$dev/${child##*/}
        [ -b "$device" ] || continue
        # Never accept a volume on another disk just because the label matches.
        label=$(blkid -p -s LABEL -o value "$device" 2>/dev/null) || continue
        [ "$label" = NWDEBUG ] || continue
        fs=$(blkid -p -s TYPE -o value "$device" 2>/dev/null) || continue
        uuid=$(blkid -p -s UUID -o value "$device" 2>/dev/null) || continue
        [ "$fs" = vfat ] && [ "$uuid" = 4E57-4442 ] || continue
        [ "$(cat "$child/ro")" = 0 ] || { reason=read_only; return 1; }
        [ -z "$found" ] || { reason=ambiguous_volume; return 1; }
        found=$device
        number=$(cat "$child/dev")
    done
    [ -n "$found" ] || { reason=no_volume; return 1; }
    printf '%s\n' "$number" > "$run/devnum"
    if ! mounted_here; then
        # Refuse foreign mounts on our mountpoint, even within a live session.
        awk -v p="$volume" '$5==p{yes=1}END{exit yes?1:0}' "$proc/self/mountinfo" || { reason=mount_conflict; return 1; }
        mount -t vfat -o ro,nosuid,nodev,noexec,umask=077 "$found" "$volume" || { reason=mount_failed; return 1; }
        if [ "$(cat "$volume/.newworld-debug" 2>/dev/null)" != 'NewWorld USB diagnostics v1' ]; then
            umount "$volume" || :; reason=marker_mismatch; return 1
        fi
        if ! mount -t vfat -o remount,rw,sync,nosuid,nodev,noexec,umask=077 "$found" "$volume"; then
            umount "$volume" || :; reason=read_only; return 1
        fi
    fi
    [ "$(cat "$volume/.newworld-debug" 2>/dev/null)" = 'NewWorld USB diagnostics v1' ] || { reason=marker_mismatch; return 1; }
    mounted_here || { reason=mount_conflict; return 1; }
    avail=$(df -Pk "$volume" | awk 'END{print $4}')
    case $avail in ''|*[!0-9]*) reason=no_space; return 1;; esac
    [ "$avail" -ge 64 ] || { reason=no_space; return 1; }
}
restore() {
    [ -f "$run/started" ] || return 1
    if [ -s "$run/reason" ]; then reason=$(cat "$run/reason"); fi
    if [ "$reason" = none ] && [ -s "$run/relative" ] && mounted_here; then
        relative=$(cat "$run/relative")
        persistent=yes
    fi
    if [ -s "$run/progress" ]; then read -r phase percent < "$run/progress" || :; fi
    return 0
}
start_log() {
    if restore; then
        case $reason in
            no_medium|no_volume) [ ! -f "$run/terminal" ] || return ;;
            *) return ;;
        esac
    fi
    [ -f "$ram" ] || : > "$ram"
    reason=none
    if select_volume; then
        short=$(tr -cd 'a-f0-9' < "$proc/sys/kernel/random/boot_id" | cut -c1-10)
        if [ "${#short}" -ne 10 ]; then reason=boot_identity; fi
        if [ "$reason" = none ]; then
            attempt_tag=
            if [ -f "$run/attempt" ]; then attempt_tag=-$(cat "$run/attempt"); fi
            relative=NewWorld/Logs/$(date -u '+%Y%m%d-%H%M%S')-"$short"$attempt_tag.log
            if mkdir -p "$volume/NewWorld/Logs" && (set -C; : > "$volume/$relative"); then
                persistent=yes
                printf '%s\n' "$relative" > "$run/relative"
            else
                relative=; reason=write_failed
            fi
        fi
    fi
    printf '%s\n' "$reason" > "$run/reason"
    touch "$run/started"
    append "NEWWORLD USB LOG v1 mode=$mode"
    if [ "$persistent" = yes ]; then status_write running; else status_write unavailable; fi
}
retry_install() {
    [ "$mode" = install ] || return 2
    if [ "$(cat "$run/terminal" 2>/dev/null || :)" = failed ]; then
        previous=$(cat "$run/attempt" 2>/dev/null || printf 1)
        case $previous in ''|*[!0-9]*) return 1;; esac
        printf '%s\n' "$((previous+1))" > "$run/attempt"
        # Preserve the previous attempt and all of its diagnostics. Only these
        # root-owned per-attempt records in RAM need to be reset.
        mv "$ram" "$run/attempt-$previous.log"
        rm -f "$run/started" "$run/relative" "$run/progress" "$run/terminal" "$run/reason"
        start_log
        snapshot
    else
        start_log
    fi
}
kernel_summary() {
    # Summarise diagnostic categories without saving raw kernel messages,
    # which may contain machine identifiers or unrelated device data.
    if command -v dmesg >/dev/null 2>&1; then
        counts=$(dmesg 2>/dev/null | awk '
            {s=tolower($0)}
            s ~ /i\/o error|medium error|buffer i\/o/ {io++}
            s ~ /firmware/ && s ~ /failed|error|not found/ {fw++}
            s ~ /acpi/ && s ~ /error|failed/ {acpi++}
            s ~ /drm|gpu/ && s ~ /error|failed|timed out/ {gpu++}
            s ~ /usb/ && s ~ /error|failed|over.current/ {usb++}
            END {printf "io_errors=%d firmware_warnings=%d acpi_warnings=%d graphics_warnings=%d usb_warnings=%d",io,fw,acpi,gpu,usb}')
        append "kernel_message_counts $counts"
    fi
}
snapshot() {
    firmware=BIOS
    if [ -d "$sys/firmware/efi" ]; then firmware=UEFI; fi
    fwbits=unknown
    if [ -r "$sys/firmware/efi/fw_platform_size" ]; then fwbits=$(first "$sys/firmware/efi/fw_platform_size"); fi
    append "kernel=$(uname -r) architecture=$(uname -m) firmware=$firmware firmware_bits=$fwbits"
    cpu=$(awk -F ': ' '/^model name/{print $2;exit}' "$proc/cpuinfo" | cut -c1-100 | tr -cd 'A-Za-z0-9 .()@:_+-')
    memory=$(awk '/^MemTotal:/{print $2;exit}' "$proc/meminfo")
    cores=$(awk '/^processor[[:space:]]*:/{n++}END{print n+0}' "$proc/cpuinfo")
    append "cpu=$cpu logical_cpus=$cores memory_kib=$memory"
    flags=$(awk '/^flags[[:space:]]*:/{s=" "$0" ";printf "long_mode=%d pae=%d sse3=%d virtualization=%d", (s~/ lm /), (s~/ pae /), (s~/ pni | sse3 /), (s~/ vmx | svm /);exit}' "$proc/cpuinfo")
    [ -z "$flags" ] || append "cpu_features $flags"
    for node in "$sys"/class/block/*; do
        [ -r "$node/size" ] && [ ! -f "$node/partition" ] || continue
        name=${node##*/}; case $name in loop*|ram*|zram*|dm-*|md*) continue;; esac
        model=unknown; [ ! -r "$node/device/model" ] || model=$(first "$node/device/model")
        append "disk=$name model=$model sectors=$(first "$node/size") read_only=$(first "$node/ro") removable=$(first "$node/removable")"
    done
    for card in "$sys"/bus/pci/devices/*; do
        [ -r "$card/class" ] || continue
        class=$(first "$card/class")
        case $class in 0x01*|0x02*|0x03*|0x04*|0x0c03*) ;; *) continue;; esac
        driver=unbound; [ ! -L "$card/driver" ] || driver=$(basename "$(readlink -f "$card/driver")")
        append "pci_class=$class vendor=$(first "$card/vendor") device=$(first "$card/device") driver=$driver"
    done
    guard=/usr/lib/newworld-installer/install-disk
    if [ -x "$guard" ]; then
        if "$guard" inspect > "$run/temporary-probe" 2>"$run/guard-error"; then selection=one_eligible_disk
        else
            selection=unavailable
            case $(cat "$run/guard-error") in
                *'too small'*) selection=insufficient_capacity;;
                *'exactly one'*) selection=no_single_target;;
                *mounted*|*'active storage'*|*'active swap'*) selection=target_in_use;;
                *'Cannot classify'*) selection=unknown_device;;
            esac
        fi
        append "read_only_target_check=$selection"
        rm -f "$run/temporary-probe" "$run/guard-error"
    fi
    kernel_summary
}
checkpoint() {
    phase=$1; percent=$2
    case $phase in waiting|prepare|partition|copy|packages|configure|bootloader|finalize|hardware|verify) ;; *) exit 2;; esac
    case $percent in 0|[1-9]|[1-9][0-9]|100) ;; *) exit 2;; esac
    record="$phase $percent"
    if [ -f "$run/progress" ] && [ "$(cat "$run/progress")" = "$record" ]; then return; fi
    printf '%s\n' "$record" > "$run/progress"
    append "stage=$phase percent=$percent"
    if [ "$persistent" = yes ]; then status_write running; else status_write unavailable; fi
}
finish_log() {
    case $1 in ok) term=complete; phase=finalize; percent=100; estimate=0;; failed) term=failed; estimate=null;; *) exit 2;; esac
    [ "$1" = ok ] || kernel_summary
    append "RESULT=$1 final_stage=$phase percent=$percent"
    if [ "$persistent" = yes ]; then
        if sync -f "$volume/$relative" 2>/dev/null || sync; then status_write "$term"; else persist_failed write_failed; fi
    else status_write unavailable; fi
    printf '%s\n' "$term" > "$run/terminal"
}
medium_files() {
    for media in /cdrom /run/live/medium /lib/live/mount/medium /run/initramfs/live; do
        [ -r "$media/sha256sum.txt" ] && [ -r "$media/.disk/newworld-universal" ] || continue
        root=$media
        return 0
    done
    return 1
}
diagnose() {
    start_log
    begin=$(cut -d. -f1 "$proc/uptime")
    checkpoint hardware 5
    snapshot
    checkpoint verify 28
    ok=yes
    if medium_files; then
        # Check the menu, both kernels, and the selected installer initrd.
        file_set='boot/grub/grub.cfg isolinux/isolinux.cfg newworld/universal.cfg live/vmlinuz install.386/vmlinuz'
        case $(uname -m) in x86_64) file_set="$file_set live/initrd.img";; *) file_set="$file_set install.386/gtk/initrd.gz";; esac
        i=0
        for member in $file_set; do
            expected=$(awk -v name="./$member" '$2==name {print $1;exit}' "$root/sha256sum.txt")
            measured=
            if [ -n "$expected" ] && [ -r "$root/$member" ]; then
                measured=$(sha256sum "$root/$member") || measured=
                measured=${measured%% *}
            fi
            if [ -n "$expected" ] && [ "$expected" = "$measured" ]; then outcome=ok
            else outcome=failed; ok=no; fi
            append "media_check=$outcome path=$member"
            i=$((i+1)); value=$((28+i*68/6))
            elapsed=$(($(cut -d. -f1 "$proc/uptime")-begin))
            estimate=$((elapsed*(100-value)/value)); [ "$estimate" -gt 0 ] || estimate=1
            checkpoint verify "$value"
        done
    else
        append 'media_check=failed manifest_or_release_marker_missing'; ok=no
    fi
    phase=finalize
    if [ "$ok" = no ]; then finish_log failed; return 1; fi
    finish_log ok
    [ "$persistent" = yes ]
}

case ${1:-} in
    start) [ "$#" -eq 1 ] || exit 2; start_log ;;
    retry) [ "$#" -eq 1 ] || exit 2; retry_install ;;
    snapshot) [ "$#" -eq 1 ] || exit 2; start_log; snapshot ;;
    event) [ "$#" -eq 3 ] || exit 2; start_log; [ -f "$run/terminal" ] || checkpoint "$2" "$3" ;;
    finish) [ "$#" -eq 2 ] || exit 2; start_log; [ -f "$run/terminal" ] || finish_log "$2" ;;
    diagnose) [ "$#" -eq 1 ] && [ "$mode" = debug ] || exit 2; diagnose ;;
    *) exit 2 ;;
esac
