#!/usr/bin/env bash
# Run this script on a reTerminal that has booted over the network (or any Pi with network).
# It registers with the provisioning dashboard and waits for Backup or Deploy, then performs the action.
# Usage: PROVISIONING_SERVER=http://192.168.1.10:5000 ./provisioning-client.sh
# Requires: curl, and for deploy/backup: enough space and write access to eMMC (e.g. /dev/mmcblk0).

set -e
BASE_URL="${PROVISIONING_SERVER:-http://192.168.1.10:5000}"
BASE_URL="${BASE_URL%/}"
EMMC_DEV="${EMMC_DEV:-/dev/mmcblk0}"
MAC=$(cat /sys/class/net/eth0/address 2>/dev/null || cat /sys/class/net/enp*/address 2>/dev/null | head -1 || echo "unknown")
IP=$(hostname -I 2>/dev/null | awk '{print $1}' || echo "")

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 status=progress conv=fsync
    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
    exit 0
  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 status=progress 2>/dev/null | curl -s -X POST -T - "$upload_url"
    echo "Backup done. Disabling network boot on server."
    curl -s -X POST "$BASE_URL/api/action-done?mac=$MAC" || true
    exit 0
  fi

  if [[ "$action" == "reboot" ]]; then
    echo "Boot normally: rebooting..."
    reboot -f 2>/dev/null || exec reboot 2>/dev/null || exit 0
  fi

  sleep 5
done
