#!/bin/bash
# Fennec OS installer: writes the Fennec OS disk image from the install stick
# onto an internal disk. The disk is wiped completely.
#
# The stick (written by Rufus in ISO mode, or dd) carries:
#   smartfox/smartfox.raw.zst   the disk image (zstd)
#   smartfox/smartfox.size      its uncompressed size in bytes
#
# After writing, the GPT backup header is moved to the end of the disk and the
# GUIDs are made unique. On first boot the installed system creates its data
# partition (/var) in the remaining space (systemd-repart).
set -u

SRC=/run/sf-src
PAYLOAD=smartfox/smartfox.raw.zst

say() { printf '%s\n' "$*"; }

banner() {
    clear
    say ""
    say "   Fennec OS telepítő"
    say "   ================="
    say ""
}

finish() {
    say ""
    say "   Enter: újraindítás   ·   k + Enter: kikapcsolás   ·   s + Enter: parancssor"
    read -r a
    case "$a" in
        s | S) exec /bin/bash -l ;;
        k | K) systemctl poweroff ;;
        *) systemctl reboot ;;
    esac
    sleep infinity
}

die() {
    say ""
    say "   HIBA: $*"
    finish
}

# Finds the partition (or whole disk, for dd-written sticks) with the payload
# and mounts it at $SRC. USB sticks can take a few seconds to show up.
find_payload() {
    mkdir -p "$SRC"
    for _ in $(seq 40); do
        while read -r dev fstype; do
            case "$fstype" in vfat | iso9660 | exfat | ntfs) ;; *) continue ;; esac
            mount -o ro "$dev" "$SRC" 2>/dev/null || continue
            if [ -f "$SRC/$PAYLOAD" ]; then
                echo "$dev"
                return 0
            fi
            umount "$SRC"
        done < <(lsblk -rpno NAME,FSTYPE)
        sleep 1
    done
    return 1
}

# Latin-2 console font (ő, ű), large on TV-sized screens.
font=Lat2-Terminus16
w=$(cut -d, -f1 /sys/class/graphics/fb0/virtual_size 2>/dev/null || echo 0)
[ "${w:-0}" -ge 1600 ] && font=Lat2-Terminus32x16
setfont "$font" 2>/dev/null

human() { numfmt --to=iec --suffix=B --format=%.1f "$1"; }

banner
say "   A telepítő pendrive keresése…"
SRC_DEV=$(find_payload) || die "Nem találom a telepítő fájlokat ($PAYLOAD) egyik meghajtón sem."
SRC_DISK=$(lsblk -npo PKNAME "$SRC_DEV" | head -1)
[ -n "$SRC_DISK" ] || SRC_DISK=$SRC_DEV
NEED=$(cat "$SRC/smartfox/smartfox.size" 2>/dev/null || echo 0)
VERSION=$(cat "$SRC/smartfox/version" 2>/dev/null || echo "")

# Candidate disks: everything except the stick itself, optical/loop/zram
# devices and disks too small for the image.
mapfile -t DISKS < <(
    lsblk -dbpno NAME,SIZE,TYPE | while read -r name size type; do
        [ "$type" = disk ] || continue
        [ "$name" = "$SRC_DISK" ] && continue
        case "$name" in /dev/loop* | /dev/zram* | /dev/sr* | /dev/ram*) continue ;; esac
        [ "$size" -ge $((NEED + 1024 * 1024 * 1024)) ] || continue
        echo "$name"
    done
)

describe() {
    local d=$1 size model tran
    size=$(lsblk -dbno SIZE "$d")
    model=$(lsblk -dno MODEL "$d" | sed 's/ *$//')
    tran=$(lsblk -dno TRAN "$d" | sed 's/ *$//')
    printf '%s  ·  %s  ·  %s%s' "$d" "$(human "$size")" "${model:-ismeretlen típus}" "${tran:+  ($tran)}"
}

banner
[ -n "$VERSION" ] && say "   Verzió: $VERSION" && say ""
[ "${#DISKS[@]}" -gt 0 ] || die "Nincs olyan belső lemez, amire telepíteni lehetne (legalább $(human $((NEED + 1024 * 1024 * 1024))) kell)."

say "   Melyik lemezre telepítsem a Fennec OS-t?"
say ""
for i in "${!DISKS[@]}"; do
    say "     $((i + 1)))  $(describe "${DISKS[$i]}")"
    lsblk -no NAME,SIZE,FSTYPE,LABEL "${DISKS[$i]}" | tail -n +2 | sed 's/^/            /'
done
say ""
while :; do
    if [ "${#DISKS[@]}" -eq 1 ]; then
        printf '   Válassz (1, vagy q = kilépés): '
    else
        printf '   Válassz (1-%s, vagy q = kilépés): ' "${#DISKS[@]}"
    fi
    read -r pick
    case "$pick" in q | Q) finish ;; esac
    if [[ "$pick" =~ ^[0-9]+$ ]] && [ "$pick" -ge 1 ] && [ "$pick" -le "${#DISKS[@]}" ]; then
        TARGET=${DISKS[$((pick - 1))]}
        break
    fi
done

banner
say "   FIGYELEM: a lemezen MINDEN adat törlődik:"
say ""
say "     $(describe "$TARGET")"
say ""
printf '   A folytatáshoz írd be: igen   '
read -r ok
[ "$ok" = igen ] || finish

banner
say "   Telepítés ide: $(describe "$TARGET")"
say ""
say "   1/3  Lemez törlése…"
umount -q "$TARGET"* 2>/dev/null
wipefs -qa "$TARGET" || die "A lemez törlése nem sikerült."

say "   2/3  Kiírás ($(human "$NEED"))…"
zstd -dcq "$SRC/$PAYLOAD" | dd of="$TARGET" bs=4M iflag=fullblock oflag=direct status=progress
st=("${PIPESTATUS[@]}")
[ "${st[0]}" = 0 ] && [ "${st[1]}" = 0 ] || die "A kiírás nem sikerült."
sync

say ""
say "   3/3  Befejezés…"
# Backup GPT to the real end of the disk, fresh GUIDs for this machine.
sgdisk -q -e -G -A 2:clear:59 "$TARGET" >/dev/null || die "A partíciós tábla javítása nem sikerült."
partx -u "$TARGET" 2>/dev/null
udevadm settle

# A unique machine id (DHCP lease, journal) on the otherwise read-only root.
ROOT=$(lsblk -rpno NAME,PARTN "$TARGET" | awk '$2 == 2 { print $1 }')
if [ -n "$ROOT" ] && mkdir -p /run/sf-root && mount "$ROOT" /run/sf-root; then
    systemd-id128 new >/run/sf-root/etc/machine-id
    umount /run/sf-root
fi

# Boot entry, so firmware that ignores the fallback path still finds it.
ESP=$(lsblk -rpno NAME,PARTN "$TARGET" | awk '$2 == 1 { print $1 }')
if [ -d /sys/firmware/efi/efivars ] && [ -n "$ESP" ]; then
    efibootmgr -q -c -d "$TARGET" -p 1 -L "Fennec OS" -l '\EFI\systemd\systemd-bootx64.efi' 2>/dev/null ||
        say "   (A UEFI boot bejegyzés nem jött létre, a gép a tartalék útvonalról indul.)"
fi
sync
umount "$SRC" 2>/dev/null

banner
say "   Kész! A Fennec OS telepítve: $TARGET"
say ""
say "   Húzd ki a pendrive-ot, majd nyomj Entert az újraindításhoz."
say "   Az első indításkor a rendszer létrehozza az adatpartíciót, ez néhány másodperc."
finish
