#!/bin/sh
# /init — HDGL Phi-Lattice Alpine (Slot4096)
# Expands hdgl.dn+hdgl.tick → 4096 SLOT values via phi-fold
# Configures OS from field state
# Starts ll_analog daemon (concurrent analog substrate)
# No Docker. No Python. Pure sh + C (ll_analog).

set -e

mount -t proc  proc  /proc
mount -t sysfs sysfs /sys
mount -t devtmpfs devtmpfs /dev 2>/dev/null || mdev -s

CMDLINE=$(cat /proc/cmdline)
HDGL_DN="88888888"
HDGL_TICK="00000000"
for token in $CMDLINE; do
    case "$token" in
        hdgl.dn=*)   HDGL_DN="${token#hdgl.dn=}"   ;;
        hdgl.tick=*) HDGL_TICK="${token#hdgl.tick=}" ;;
    esac
done

echo "[init] Slot4096  dn=$HDGL_DN  tick=$HDGL_TICK"

# phi_fold: expand index i into slot value using dn+tick as seeds
# Returns float in [0,1] written to /lattice/slots/$i
phi_fold_slot() {
    local i=$1
    awk -v i="$i" -v dn="$DN_DEC" -v tick="$TICK_DEC" 'BEGIN {
        M32=4294967295
        a=(i*2654435769)%M32; if(a<0)a+=M32
        b=(dn*2654435761)%M32; if(b<0)b+=M32
        c=(tick*2654136499)%M32; if(c<0)c+=M32
        v=xor(xor(a,b),c)%M32; if(v<0)v+=M32
        printf "%.16f\n",v/M32
    }' > /lattice/slots/$i
}

DN_DEC=$(printf '%d' "0x$HDGL_DN" 2>/dev/null || echo 2290649224)
TICK_DEC=$(printf '%d' "0x$HDGL_TICK" 2>/dev/null || echo 0)

mkdir -p /lattice/slots /run/lattice
mount -t ramfs -o size=32m ramfs /lattice 2>/dev/null
mkdir -p /lattice/slots /run/lattice

# Pre-compute slots needed for OS config
for s in 0 1 2 3 4 5 8 9 16 17 18 23; do phi_fold_slot $s; done

get_slot() { cat /lattice/slots/$1 2>/dev/null || echo "0.5"; }

HOSTNAME=$(printf "phi4096-%s" "$HDGL_DN")
TZ_IDX=$(awk -v s="$(get_slot 16)" 'BEGIN{printf "%d",s*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
    [ "$TZ_COUNT" -eq "$TZ_IDX" ] && TIMEZONE="$tz" && break
    TZ_COUNT=$((TZ_COUNT+1))
done

SWAPPINESS=$(awk -v s="$(get_slot 23)" 'BEGIN{printf "%d",s*100}')
PID_MAX=$(awk -v s="$(get_slot 8)"  'BEGIN{printf "%d",32768+int(s*32768)}')
DIRTY_RATIO=$(awk -v s="$(get_slot 9)"  'BEGIN{printf "%d",5+int(s*20)}')
SOMAXCONN=$(awk -v s="$(get_slot 4)"  'BEGIN{printf "%d",128+int(s*896)}')
NICE=$(awk -v s="$(get_slot 17)" 'BEGIN{printf "%d",-20+int(s*40)}')
LATTICE_UID=$(awk -v s="$(get_slot 18)" 'BEGIN{printf "%d",1000+int(s*59000)}')
PKG_BITS=$(awk -v s="$(get_slot 5)"  'BEGIN{printf "%d",int(s*255)}')
PACKAGES="busybox util-linux"
[ $(( PKG_BITS & 1 )) -eq 1 ] && PACKAGES="$PACKAGES curl"
[ $(( PKG_BITS & 2 )) -eq 1 ] && PACKAGES="$PACKAGES bash"
[ $(( PKG_BITS & 4 )) -eq 1 ] && PACKAGES="$PACKAGES htop"

echo "[init] host=$HOSTNAME tz=$TIMEZONE uid=$LATTICE_UID nice=$NICE"

# Write state files
{ printf "LATTICE_SEED=0x%s%s\nLATTICE_N=4096\nLATTICE_STEPS=0\n" "$HDGL_DN" "$HDGL_TICK"
  printf "LATTICE_HOST=%s\nLATTICE_DN=0x%s\nLATTICE_TICK=0x%s\n" "$HOSTNAME" "$HDGL_DN" "$HDGL_TICK"
  printf "LATTICE_SWAPPINESS=%s\nLATTICE_PID_MAX=%s\nLATTICE_SOMAXCONN=%s\n" "$SWAPPINESS" "$PID_MAX" "$SOMAXCONN"
  printf "LATTICE_UID=%s\nLATTICE_NICE=%s\nLATTICE_TZ=%s\n" "$LATTICE_UID" "$NICE" "$TIMEZONE"
} | tee /lattice/state.env > /run/lattice/state
chmod 444 /lattice/state.env /run/lattice/state

# Mount root
ROOT_MOUNTED=0
for dev in /dev/sda2 /dev/sda1 /dev/vda2 /dev/vda1; do
    mount -t ext4 "$dev" /mnt/root 2>/dev/null && ROOT_MOUNTED=1 && echo "[init] root=$dev" && break
done
[ "$ROOT_MOUNTED" -eq 0 ] && echo "[init] no root — recovery" && exec /bin/sh

mkdir -p /mnt/root/etc/sysctl.d /mnt/root/etc/apk /mnt/root/etc/profile.d
mkdir -p /mnt/root/run/lattice /mnt/root/lattice/slots
mkdir -p /mnt/root/usr/local/bin /mnt/root/usr/src

# Entropy
printf '%s%s' "$HDGL_DN" "$HDGL_TICK" > /dev/urandom 2>/dev/null || true

# sysctl (slot[23..30])
cat > /mnt/root/etc/sysctl.d/99-lattice.conf << EOSYSCTL
vm.swappiness = $SWAPPINESS
kernel.pid_max = $PID_MAX
vm.dirty_ratio = $DIRTY_RATIO
net.core.somaxconn = $SOMAXCONN
kernel.randomize_va_space = 0
EOSYSCTL
sysctl -p /mnt/root/etc/sysctl.d/99-lattice.conf 2>/dev/null || true

# hostname, timezone, APK
echo "$HOSTNAME" > /mnt/root/etc/hostname
ln -sf "/usr/share/zoneinfo/$TIMEZONE" /mnt/root/etc/localtime 2>/dev/null || true
echo "$TIMEZONE" > /mnt/root/etc/timezone
printf 'https://dl-cdn.alpinelinux.org/alpine/latest-stable/main\nhttps://dl-cdn.alpinelinux.org/alpine/latest-stable/community\n' > /mnt/root/etc/apk/repositories
echo "[lattice] Installing: $PACKAGES"
chroot /mnt/root apk add -q $PACKAGES 2>/dev/null || true

# slot4096 user
chroot /mnt/root /bin/sh -c "
    addgroup -g $LATTICE_UID slot4096 2>/dev/null||true
    adduser -u $LATTICE_UID -G slot4096 -h /home/slot4096 -s /bin/sh -D slot4096 2>/dev/null||true
    mkdir -p /home/slot4096 && chown slot4096:slot4096 /home/slot4096
" 2>/dev/null || true

# /etc/profile.d/lattice.sh
cat > /mnt/root/etc/profile.d/lattice.sh << EOPROF
export LATTICE_N=4096 LATTICE_HOST=$HOSTNAME LATTICE_TZ=$TIMEZONE
export LATTICE_UID=$LATTICE_UID LATTICE_NICE=$NICE
export HDGL_DN=0x$HDGL_DN HDGL_TICK=0x$HDGL_TICK
alias lattice='cat /lattice/state.env'
alias slots='ls /lattice/slots/ | head -32'
alias ll-status='cat /run/lattice/state'
alias lscpu='lattice-lscpu'
export PS1='\[\033[1;35m\]slot4096@$HOSTNAME:\[\033[1;32m\]\w\[\033[0m\]$ '
EOPROF

# ~/.bashrc
cat > /mnt/root/home/slot4096/.bashrc << 'EOBASH'
. /etc/profile.d/lattice.sh
alias ls='ls --color=auto'
alias ll='ls -la'
EOBASH
cp /mnt/root/home/slot4096/.bashrc /mnt/root/home/slot4096/.bash_profile
chroot /mnt/root chown slot4096:slot4096 /home/slot4096/.bashrc /home/slot4096/.bash_profile 2>/dev/null||true

# /etc/issue and /etc/os-release
printf '\nSlot4096 Phi-Lattice Alpine\n  dn=0x%s  tick=0x%s  host=%s\n\n' \
    "$HDGL_DN" "$HDGL_TICK" "$HOSTNAME" > /mnt/root/etc/issue
cat > /mnt/root/etc/os-release << EOREL
NAME="Alpine Linux"
PRETTY_NAME="Slot4096 Phi-Lattice Alpine"
LATTICE_DN=0x$HDGL_DN
LATTICE_TICK=0x$HDGL_TICK
LATTICE_HOST=$HOSTNAME
EOREL

# /etc/motd
cat > /mnt/root/etc/motd << EOMOTD
+--------------------------------------------------------------+
|  Slot4096 Phi-Lattice Alpine Linux                           |
|  dn   : 0x$HDGL_DN                              |
|  tick : 0x$HDGL_TICK                              |
|  host : $HOSTNAME                        |
|  tz   : $TIMEZONE                                    |
|  uid  : $LATTICE_UID    nice: $NICE    slots: 4096         |
+--------------------------------------------------------------+
|  analog substrate: /lattice/slots/  /run/lattice/state      |
|  ll_analog daemon: running (8D Kuramoto + exact APA)        |
+--------------------------------------------------------------+
EOMOTD

# lattice-lscpu
cat > /mnt/root/usr/local/bin/lattice-lscpu << ELCPU
#!/bin/sh
printf '\n+--------------------------------------------------------------+\n'
printf '|  Slot4096 Phi-Lattice Processor                             |\n'
printf '|  seed: 0x%s%s                    |\n' "$HDGL_DN" "$HDGL_TICK"
printf '|  slots: 4096   dn: 0x%s                       |\n' "$HDGL_DN"
printf '+--------------------------------------------------------------+\n\n'
lscpu 2>/dev/null | sed 's/Model name:.*/Model name:        Slot4096 Phi-Lattice/'
printf '\nAnalog substrate:\n'; cat /run/lattice/state 2>/dev/null | head -6
ELCPU
chmod +x /mnt/root/usr/local/bin/lattice-lscpu

# Copy lattice state to root
cp /lattice/state.env /mnt/root/lattice/state.env 2>/dev/null || true
cp /run/lattice/state /mnt/root/run/lattice/state 2>/dev/null || true
cp /lattice/slots/* /mnt/root/lattice/slots/ 2>/dev/null || true

# Start ll_analog concurrent substrate
# ll_analog (from ll_analog.c in Analog-Prime-main) is the canonical
# 8D Kuramoto + arbitrary precision Lucas-Lehmer substrate.
# When running as a daemon with our lattice state, it:
#   1. Seeds 8D oscillators from phi_fold(dn, tick, i)
#   2. Runs Pluck→Sustain→FineTune→Lock phase progression
#   3. Writes updated slot values to /lattice/slots/ every ANA_SHA_INTERVAL
#   4. Writes /run/lattice/state on phase transitions
if [ -x /mnt/root/sbin/ll_analog ]; then
    chroot /mnt/root /bin/sh -c "
        nohup /sbin/ll_analog \
            --dn 0x$HDGL_DN --tick 0x$HDGL_TICK \
            --slots /lattice/slots/ --state /run/lattice/state \
            >/var/log/ll_analog.log 2>&1 &
        echo \$! > /run/ll_analog.pid
    " 2>/dev/null || true
    echo "[lattice] ll_analog started (pid=$(cat /mnt/root/run/ll_analog.pid 2>/dev/null))"
elif [ -f /usr/src/ll_analog.c ]; then
    cp /usr/src/ll_analog.c /mnt/root/usr/src/ll_analog.c
    chroot /mnt/root /bin/sh -c "
        gcc -O2 -o /sbin/ll_analog /usr/src/ll_analog.c -lm &&
        nohup /sbin/ll_analog \
            --dn 0x$HDGL_DN --tick 0x$HDGL_TICK \
            --slots /lattice/slots/ --state /run/lattice/state \
            >/var/log/ll_analog.log 2>&1 &
    " 2>/dev/null || true
    echo "[lattice] ll_analog compiled and started"
else
    # Shell fallback: phi-fold ticker
    cat > /mnt/root/usr/local/bin/ll_tick.sh << 'LLTICK'
#!/bin/sh
DN=$(grep LATTICE_DN /lattice/state.env | cut -d= -f2 | tr -d '0x')
DN_D=$(printf '%d' "0x$DN" 2>/dev/null || echo 2290649224)
STEP=0
while true; do
    STEP=$((STEP+1))
    DN_D=$(awk -v d="$DN_D" -v s="$STEP" 'BEGIN{M=4294967295;printf "%d\n",(d*2654435769+s)%M}')
    printf 'LATTICE_STEPS=%d\nLATTICE_DN=0x%08X\n' "$STEP" "$DN_D" > /run/lattice/state
    N=0; while [ $N -lt 32 ]; do
        awk -v i=$N -v d="$DN_D" -v s="$STEP" \
            'BEGIN{M=4294967295;v=(i*2654435769+d*2654435761+s)%M;if(v<0)v+=M;printf "%.16f\n",v/M}' \
            > /lattice/slots/$N 2>/dev/null
        N=$((N+1))
    done
    sleep 3
done
LLTICK
    chmod +x /mnt/root/usr/local/bin/ll_tick.sh
    chroot /mnt/root nohup /usr/local/bin/ll_tick.sh >/dev/null 2>&1 &
    echo "[lattice] ll_tick.sh (shell fallback) started"
fi

# Background: expand remaining slots 32..4095
(
    n=32
    while [ $n -lt 4096 ]; do
        phi_fold_slot $n
        cp /lattice/slots/$n /mnt/root/lattice/slots/$n 2>/dev/null || true
        n=$((n+1))
    done
    echo "[lattice] All 4096 slots expanded"
) &

# Final status
cat /mnt/root/etc/motd
echo "[lattice] Switching root — analog substrate running concurrently"
exec switch_root /mnt/root /sbin/init
