#!/bin/sh
# POSIX sh version for initramfs. Registers with dashboard and runs Deploy or Backup.
# PROVISIONING_SERVER must be set (e.g. http://10.20.50.1:5000).

BASE_URL="${PROVISIONING_SERVER:-http://10.20.50.1:5000}"
BASE_URL="${BASE_URL%/}"
EMMC_DEV="${EMMC_DEV:-/dev/mmcblk0}"

get_mac() {
  cat /sys/class/net/eth0/address 2>/dev/null || \
  cat /sys/class/net/enp0s1f0/address 2>/dev/null || \
  echo "unknown"
}

get_ip() {
  # Prefer IP captured by init; fallback to ip (match "inet 1.2.3.4/..." to skip inet6)
  if [ -f /tmp/client_ip ] && [ -s /tmp/client_ip ]; then
    cat /tmp/client_ip
    return
  fi
  ip addr show dev eth0 2>/dev/null | awk '/inet [0-9]/ { print $2; exit }' | cut -d/ -f1
}

MAC=$(get_mac)
IP=$(get_ip)

echo "Registering with $BASE_URL (MAC=$MAC IP=$IP)..."
curl -s -X POST -H "Content-Type: application/json" \
  -d "{\"mac\":\"$MAC\",\"ip\":\"$IP\"}" "$BASE_URL/api/register-device" || true

echo "Polling for action (Backup or Deploy)..."
while true; do
  resp=$(curl -s "$BASE_URL/api/device-action-poll?mac=$MAC" 2>/dev/null || echo '{"action":"wait"}')
  action=$(echo "$resp" | grep -o '"action":"[^"]*"' | cut -d'"' -f4)
  url=$(echo "$resp" | grep -o '"url":"[^"]*"' | cut -d'"' -f4)
  upload_url=$(echo "$resp" | grep -o '"upload_url":"[^"]*"' | cut -d'"' -f4)

  if [ "$action" = "deploy" ] && [ -n "$url" ]; then
    echo "Deploy: downloading image and writing to $EMMC_DEV..."
    if [ ! -b "$EMMC_DEV" ]; then
      echo "Error: $EMMC_DEV not found"
      sleep 10
      continue
    fi
    curl -sL "$url" | dd of="$EMMC_DEV" bs=4M conv=fsync 2>&1
    sync
    echo "Deploy done. Disabling network boot on server so device boots from eMMC next time."
    curl -s -X POST "$BASE_URL/api/action-done?mac=$MAC" || true
    echo "Rebooting in 3 seconds..."
    sleep 3
    reboot -f 2>/dev/null || echo b > /proc/sysrq-trigger
    sleep 60
  fi

  if [ "$action" = "backup" ] && [ -n "$upload_url" ]; then
    echo "Backup: reading $EMMC_DEV and uploading..."
    if [ ! -b "$EMMC_DEV" ]; then
      echo "Error: $EMMC_DEV not found"
      sleep 10
      continue
    fi
    dd if="$EMMC_DEV" bs=4M 2>/dev/null | curl -s -X POST -T - "$upload_url"
    sync
    echo "Backup done. Disabling network boot on server."
    curl -s -X POST "$BASE_URL/api/action-done?mac=$MAC" || true
    echo "Rebooting in 3 seconds..."
    sleep 3
    reboot -f 2>/dev/null || echo b > /proc/sysrq-trigger
    sleep 60
  fi

  if [ "$action" = "reboot" ]; then
    echo "Rebooting..."
    reboot -f 2>/dev/null || echo b > /proc/sysrq-trigger
    sleep 60
  fi

  sleep 5
done
