#!/bin/sh
# Init for provisioning initramfs: bring up minimal env and run provisioning-client.sh.
# PROVISIONING_SERVER can be set via kernel cmdline: provisioning_server=http://10.20.50.1:5000

set -e
export PATH=/bin:/usr/bin
export LD_LIBRARY_PATH=/lib

echo "=== CM4 provisioning initramfs ==="
# Revision is set at build time; cat /revision.txt to confirm you have the latest initrd on TFTP
[ -f /revision.txt ] && echo "Revision: $(cat /revision.txt)" || echo "Revision: (none)"

# Minimal filesystem
mount -t proc none /proc
mount -t sysfs none /sys
mount -t devtmpfs none /dev
mkdir -p /dev/pts
mount -t devpts none /dev/pts

# Bring up eth0 (bootloader used it for TFTP but kernel starts with it down)
echo "Bringing up eth0..."
ip link set lo up 2>/dev/null || true
ip link set eth0 up 2>/dev/null || true

# Wait for link (PHY negotiation takes a few seconds after ip link set up)
echo "Waiting for link..."
for _ in 1 2 3 4 5 6 7 8 9 10; do
  ip link show eth0 2>/dev/null | grep -q 'LOWER_UP' && break
  sleep 1
done

# Get DHCP lease (foreground with retries; -q exits after obtaining lease)
if ! ip addr show eth0 2>/dev/null | grep -q 'inet [0-9]'; then
  echo "Getting DHCP lease..."
  udhcpc -i eth0 -q -T 5 -t 5 -n -s /usr/share/udhcpc/default.script 2>&1 || echo "udhcpc failed (will retry)"
fi

# /tmp for client_ip (so client can read IP without running ip/awk)
mkdir -p /tmp
mount -t tmpfs none /tmp 2>/dev/null || true

# Allow kernel cmdline to override: provisioning_server=... and rescue mode
RESCUE=0
for arg in $(cat /proc/cmdline); do
  case "$arg" in
    provisioning_server=*) export PROVISIONING_SERVER="${arg#*=}"; ;;
    provisioning_rescue=1) RESCUE=1; ;;
  esac
done
PROVISIONING_SERVER="${PROVISIONING_SERVER:-http://10.20.50.1:5000}"
export PROVISIONING_SERVER

if [ "$RESCUE" -eq 1 ]; then
  echo "=== RESCUE MODE (provisioning_rescue=1) ==="
  echo "Run /rescue-eeprom.sh to mount eMMC and change boot order (rpi-eeprom-config), then reboot."
  # Ensure shell I/O goes to serial console (some setups drop output otherwise)
  [ -c /dev/console ] && exec </dev/console >/dev/console 2>&1
  exec /bin/sh -i
fi

echo "Provisioning server: $PROVISIONING_SERVER"
# Debug: show full ip addr output on serial so we can see what the interface looks like
echo "--- ip addr show ---"
ip addr show 2>&1 || echo "(ip addr show failed)"
echo "--- end ip addr ---"
# Capture eth0 IP; retry in case DHCP is still completing
for _ in 1 2 3 4 5; do
  ip addr show dev eth0 2>/dev/null | awk '/inet [0-9]/ { print $2; exit }' | cut -d/ -f1 > /tmp/client_ip 2>/dev/null || true
  [ -s /tmp/client_ip ] && break
  echo "Waiting for IP on eth0..."
  sleep 2
done
echo "Client IP: $(cat /tmp/client_ip 2>/dev/null || echo '(none)')"
echo "Running provisioning client..."
exec /bin/sh /provisioning-client.sh
