#!/bin/sh
# lattice_crystal.sh  --  Crystal-native lattice init (Linux side)
# Generated by prime_ui [C] Crystal-Native
# Crystal: 24000000 Hz  TSC: 2808.001 MHz  Phase: 0.70085470
set -e

CRYSTAL_HZ=24000000
TSC_HZ=2808001061
CRYSTAL_PERIOD=117
STATIC_PHASE_TICK=82
STATIC_SEED=0xf32714ba8cc08987

echo ''
echo '+--------------------------------------------------------------+'
echo '|  Crystal-Native Lattice Init  (Linux / Alpine side)         |'
echo '+--------------------------------------------------------------+'
echo ''

CS=/sys/devices/system/clocksource/clocksource0/current_clocksource
[ -r "$CS" ] && printf '  Clocksource : %s\n' "$(cat $CS)" || true

# Load MSR driver and read IA32_TSC (MSR 0x10)
modprobe msr 2>/dev/null || true
command -v rdmsr >/dev/null 2>&1 || apk add --quiet msr-tools 2>/dev/null || true

if command -v rdmsr >/dev/null 2>&1; then
  TSC_HEX=$(rdmsr -p 0 0x10 2>/dev/null || echo 0)
  printf '  IA32_TSC    : 0x%s  (live crystal reading)\n' "$TSC_HEX"
  # crystal phase: TSC mod 117 ticks (one 24000000 Hz oscillation = 41.67 ns)
  # Use awk for portable integer math on large TSC values
  awk -v hex="$TSC_HEX" -v period=117 \
    'BEGIN { tsc=strtonum("0x"hex); phase=tsc%period;
             printf "  Phase tick  : %d / 117  (41.67 ns/osc)\n",phase }'
else
  echo '  [warn] msr-tools unavailable -- using static seed'
fi

mkdir -p /run/lattice
cat > /run/lattice/crystal_state << 'CSEOF'
CRYSTAL_HZ=24000000
TSC_HZ=2808001061
CRYSTAL_PERIOD=117
STATIC_PHASE_TICK=82
STATIC_SEED=0xf32714ba8cc08987
CSEOF

# Install /usr/local/bin/crystal_seed
cat > /usr/local/bin/crystal_seed << 'BINEOF'
#!/bin/sh
# crystal_seed -- read live TSC crystal phase and display lattice state
modprobe msr 2>/dev/null || true
if command -v rdmsr >/dev/null 2>&1; then
  T=$(rdmsr -p 0 0x10 2>/dev/null || echo 0)
  printf 'IA32_TSC: 0x%s\n' "$T"
  awk -v h="$T" -v p=117 'BEGIN{t=strtonum("0x"h); printf "Phase: %d/117 (41.67 ns/osc)\n",t%p}'
fi
echo '---'
cat /run/lattice/crystal_state 2>/dev/null || echo '(crystal_state not found -- run lattice_crystal.sh first)'
BINEOF
chmod +x /usr/local/bin/crystal_seed

# OpenRC init: lattice-crystal (re-seeds on boot)
cat > /etc/init.d/lattice-crystal << 'RCEOF'
#!/sbin/openrc-run
description="Phi-lattice crystal-native re-seed"
depend() { need localmount; }
start() {
  ebegin "Crystal-seeding phi-lattice"
  /usr/local/bin/crystal_seed > /run/lattice/crystal_boot.log 2>&1
  eend $?
}
RCEOF
chmod +x /etc/init.d/lattice-crystal
rc-update add lattice-crystal default 2>/dev/null || true

echo ''
echo '  [OK] /usr/local/bin/crystal_seed  installed'
echo '  [OK] OpenRC lattice-crystal  added to default runlevel'
echo '  [OK] /run/lattice/crystal_state  written'
echo ''
