#!/bin/sh
# ============================================================================
# /init — HDGL Phi-Lattice Alpine Init
# ============================================================================
#
# Runs inside the Alpine initramfs after the HDGL firmware hands off.
# Reads hdgl.dn= and hdgl.tick= from /proc/cmdline and derives OS
# configuration from them — the same logic as conscious-128-bit-floor's
# lattice_init.sh, but sourced from the live hardware field state at
# handoff time rather than pre-generated files.
#
# No Docker. No Python. Pure POSIX sh (busybox).
# ============================================================================

set -e

# ── Mount early filesystems ─────────────────────────────────────────────────
mount -t proc  proc  /proc
mount -t sysfs sysfs /sys
mount -t devtmpfs devtmpfs /dev 2>/dev/null || mdev -s

# ── Parse HDGL tokens from cmdline ──────────────────────────────────────────
CMDLINE=$(cat /proc/cmdline)

hdgl_dn=""
hdgl_tick=""
for token in $CMDLINE; do
    case "$token" in
        hdgl.dn=*)   hdgl_dn="${token#hdgl.dn=}"   ;;
        hdgl.tick=*) hdgl_tick="${token#hdgl.tick=}" ;;
    esac
done

# Defaults if firmware didn't embed tokens (fallback for non-HDGL boots)
: "${hdgl_dn:=88888888}"
: "${hdgl_tick:=00000000}"

echo "[init] hdgl.dn=$hdgl_dn  hdgl.tick=$hdgl_tick"

# ── Derive OS parameters from the field tokens ───────────────────────────────
# All derivation is pure sh arithmetic on the two 32-bit hex values.
# phi-fold: fold(x) = (x * 0x9E3779B9 + 0x6C62272E) & 0xFFFFFFFF
# Used to spread the two inputs across the parameter space.

dn_dec=$(printf '%d' "0x$hdgl_dn")
tick_dec=$(printf '%d' "0x$hdgl_tick")

# Hostname: phi-fold of dn into a 4-digit hex suffix
hn_seed=$(( (dn_dec * 2654435769 + 1817536622) & 0xFFFF ))
HOSTNAME=$(printf "phi-%04x" "$hn_seed")

# Timezone slot: tick mod 24 → one of the canonical UTC offsets
tz_idx=$(( tick_dec % 24 ))
TZ_LIST="UTC UTC+1 UTC+2 UTC+3 UTC+4 UTC+5 UTC+6 UTC+7 UTC+8 UTC+9 UTC+10 UTC+11 UTC-1 UTC-2 UTC-3 UTC-4 UTC-5 UTC-6 UTC-7 UTC-8 UTC-9 UTC-10 UTC-11 UTC-12"
tz_count=0
TIMEZONE="UTC"
for tz in $TZ_LIST; do
    if [ "$tz_count" -eq "$tz_idx" ]; then TIMEZONE="$tz"; break; fi
    tz_count=$(( tz_count + 1 ))
done

# UID: fold of dn+tick into range [1000, 60000]
uid_seed=$(( (dn_dec ^ tick_dec ^ 0xDEADBEEF) & 0xFFFF ))
LATTICE_UID=$(( 1000 + (uid_seed % 59000) ))

# Swappiness: dn bits [7:0] → range [0, 100]
SWAPPINESS=$(( dn_dec & 0xFF ))
[ "$SWAPPINESS" -gt 100 ] && SWAPPINESS=60

# pid_max: tick bits [15:8] → range [32768, 98304]
PID_MAX=$(( 32768 + (( (tick_dec >> 8) & 0xFF ) * 256) ))

# somaxconn: dn bits [23:8] → range [128, 65535]
SOMAXCONN=$(( 128 + (( (dn_dec >> 8) & 0xFFFF ) % 65407) ))

# Package set: dn bit 0 → minimal or extended
if [ $(( dn_dec & 1 )) -eq 1 ]; then
    PACKAGES="busybox util-linux"
else
    PACKAGES="busybox util-linux bash htop"
fi

echo "[init] hostname=$HOSTNAME  tz=$TIMEZONE  uid=$LATTICE_UID"
echo "[init] swappiness=$SWAPPINESS  pid_max=$PID_MAX  somaxconn=$SOMAXCONN"

# ── Mount root filesystem ────────────────────────────────────────────────────
# Try sda2, then sda1, then stay in initramfs (netboot / recovery mode)
ROOT_MOUNTED=0
for dev in /dev/sda2 /dev/sda1; do
    if mount -t ext4 "$dev" /mnt/root 2>/dev/null; then
        ROOT_MOUNTED=1
        echo "[init] root mounted from $dev"
        break
    fi
done

if [ "$ROOT_MOUNTED" -eq 0 ]; then
    echo "[init] no root partition — staying in initramfs (recovery mode)"
    echo "[init] type 'exit' to reboot or run commands directly"
    exec /bin/sh
fi

# ── Write lattice-derived config into root before switch_root ───────────────

# sysctl
mkdir -p /mnt/root/etc/sysctl.d
cat > /mnt/root/etc/sysctl.d/99-hdgl-lattice.conf << EOF
vm.swappiness=$SWAPPINESS
kernel.pid_max=$PID_MAX
net.core.somaxconn=$SOMAXCONN
kernel.randomize_va_space=0
EOF

# hostname
echo "$HOSTNAME" > /mnt/root/etc/hostname

# timezone (symlink in Alpine)
ln -sf "/usr/share/zoneinfo/$TIMEZONE" /mnt/root/etc/localtime 2>/dev/null || true
echo "$TIMEZONE" > /mnt/root/etc/timezone

# /etc/issue
cat > /mnt/root/etc/issue << EOF
Slot4096 Phi-Lattice Alpine Linux
  Dn=$hdgl_dn  tick=$hdgl_tick
  hostname=$HOSTNAME  tz=$TIMEZONE
EOF

# /etc/os-release
cat > /mnt/root/etc/os-release << EOF
ID=alpine
NAME="Alpine Linux"
PRETTY_NAME="Slot4096 Lattice-Powered Alpine Linux"
HDGL_DN=$hdgl_dn
HDGL_TICK=$hdgl_tick
HDGL_HOST=$HOSTNAME
VERSION_ID=lattice-1.0
EOF

# /etc/motd
cat > /mnt/root/etc/motd << EOF

  ╔══════════════════════════════════════════════════════╗
  ║  Phi-Lattice Alpine                                  ║
  ║  Ωₙ₊₁ = T(Ωₙ)   φ = 1.6180339887498948             ║
  ║                                                      ║
  ║  hdgl.dn   = $hdgl_dn                   ║
  ║  hdgl.tick = $hdgl_tick                   ║
  ║  hostname  = $HOSTNAME                         ║
  ║  timezone  = $TIMEZONE                           ║
  ╚══════════════════════════════════════════════════════╝

EOF

# /run/lattice — live state mountpoint
mkdir -p /mnt/root/run/lattice
mount -t tmpfs tmpfs /mnt/root/run/lattice
printf "dn=%s\ntick=%s\nhostname=%s\ntz=%s\nuid=%d\n" \
    "$hdgl_dn" "$hdgl_tick" "$HOSTNAME" "$TIMEZONE" "$LATTICE_UID" \
    > /mnt/root/run/lattice/state

# APK mirror (lattice-chosen, stable CDN)
mkdir -p /mnt/root/etc/apk
cat > /mnt/root/etc/apk/repositories << EOF
https://dl-cdn.alpinelinux.org/alpine/v3.20/main
https://dl-cdn.alpinelinux.org/alpine/v3.20/community
EOF

# Create slot4096 user if not present
if ! grep -q "slot4096" /mnt/root/etc/passwd 2>/dev/null; then
    echo "slot4096:x:$LATTICE_UID:$LATTICE_UID:Phi-Lattice User:/home/slot4096:/bin/sh" \
        >> /mnt/root/etc/passwd
    echo "slot4096:x:$LATTICE_UID:" >> /mnt/root/etc/group
    echo "slot4096:!::0:::::" >> /mnt/root/etc/shadow
    mkdir -p /mnt/root/home/slot4096
    chown "$LATTICE_UID:$LATTICE_UID" /mnt/root/home/slot4096 2>/dev/null || true
fi

# Apply sysctl before switch_root (affects running kernel)
sysctl -p /mnt/root/etc/sysctl.d/99-hdgl-lattice.conf 2>/dev/null || true

echo "[init] config written — switching root"

# ── Switch root ──────────────────────────────────────────────────────────────
exec switch_root /mnt/root /sbin/init
