#!/bin/bash
# ============================================================
#  make-box  —  build a per-server LOCKED AI-Phone bundle
#
#      ./make-box.sh "Customer A - KL office"
#
#  Registers a NEW box on the key server (its own device id + token + key),
#  copies the blank template, re-keys that copy's vault so it opens ONLY with
#  the new box's key, and writes its device.conf. The result is a ready-to-ship
#  folder under ~/customer-bundles/<slug>/ that the customer runs with:
#      sudo ./start.sh
#  Each box then appears as its OWN row on the key server (individual
#  Allow/Block, individual online/last-seen).
# ============================================================
set -e

LABEL="$*"
[ -n "$LABEL" ] || { echo "Usage: ./make-box.sh \"Customer / server name\""; exit 1; }

HERE="$(cd "$(dirname "$0")" && pwd)"
TEMPLATE="$HOME/AI-Phone-Lock-Deploy"          # blank config + latest image
MASTER="$HERE/vault-master.key"                 # opens the template vault (never shipped)
KEYSERVER_CONTAINER="ai-phone-keyserver"
KEYSERVER_URL="https://ai.mforce.asia/keyserver/unlock"
OUTROOT="$HOME/customer-bundles"

[ -d "$TEMPLATE" ] || { echo "Template not found: $TEMPLATE"; exit 1; }
[ -f "$MASTER" ]   || { echo "Master key not found: $MASTER"; exit 1; }

# slug for the folder name
SLUG=$(printf '%s' "$LABEL" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]\+/-/g; s/^-//; s/-$//')
OUT="$OUTROOT/$SLUG"
[ -e "$OUT" ] && { echo "A bundle folder already exists: $OUT (pick a different name or remove it)"; exit 1; }

echo "[1/5] creating a new box identity on the key server…"
# Generate id/token/key in the SAME format the key server uses, register it in
# devices.json (live), and print the values back.
CREDS=$(docker exec -i "$KEYSERVER_CONTAINER" node -e '
const fs=require("fs"), crypto=require("crypto");
const p="/app/devices.json";
const d=JSON.parse(fs.readFileSync(p));
const id=crypto.randomBytes(8).toString("hex");
const token=crypto.randomBytes(24).toString("hex");
const key=crypto.randomBytes(64).toString("base64");
d.devices=d.devices||{};
d.devices[id]={token,key,allowed:true,label:process.argv[1].slice(0,60),created:new Date().toISOString(),lastSeen:""};
fs.writeFileSync(p,JSON.stringify(d,null,2));
process.stdout.write(id+" "+token+" "+key);
' "$LABEL")
DEVICE_ID=$(echo "$CREDS" | cut -d' ' -f1)
TOKEN=$(echo "$CREDS" | cut -d' ' -f2)
KEY_B64=$(echo "$CREDS" | cut -d' ' -f3)
echo "    device_id=$DEVICE_ID"

echo "[2/5] reloading the key server so it knows the new box…"
docker restart "$KEYSERVER_CONTAINER" >/dev/null
# wait until it answers again
for i in $(seq 1 15); do curl -sf -o /dev/null http://127.0.0.1:8790/health && break; sleep 1; done

echo "[3/5] copying the blank template…"
mkdir -p "$OUTROOT"
cp -r "$TEMPLATE" "$OUT"
# never ship any stray key / old identity / prior boot state
rm -f "$OUT/vault.key" "$OUT/device.conf"
rm -rf "$OUT/secure" "$OUT/recordings"/* 2>/dev/null || true

echo "[4/5] re-keying this bundle's vault to the new box's key…"
WORK=$(mktemp -d)
cp "$MASTER" "$WORK/master.key"
printf '%s' "$KEY_B64" | base64 -d > "$WORK/new.key"
docker run --rm --privileged -v "$OUT:/b" -v "$WORK:/work" ubuntu:24.04 bash -c '
apt-get install -y -qq cryptsetup-bin >/dev/null 2>&1 || (apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq cryptsetup-bin >/dev/null 2>&1)
set -e
cryptsetup luksAddKey --key-file /work/master.key /b/vault.img /work/new.key
cryptsetup luksRemoveKey /b/vault.img /work/master.key
# prove: new key opens, master no longer does
cryptsetup open --readonly --key-file /work/new.key /b/vault.img chk && cryptsetup close chk
! cryptsetup open --readonly --key-file /work/master.key /b/vault.img chk2 2>/dev/null || { echo "ERROR: master key still opens the shipped vault"; exit 1; }
echo "    re-keyed OK (only the new box key opens it)"
'
rm -rf "$WORK"

echo "[5/5] writing this box's identity file…"
cat > "$OUT/device.conf" <<EOF
# This box's identity. It has NO key — it fetches the key from your key server.
DEVICE_ID=$DEVICE_ID
TOKEN=$TOKEN
KEYSERVER_URL=$KEYSERVER_URL
EOF

echo
echo "================================================================"
echo "  DONE — bundle for \"$LABEL\""
echo "  Folder:   $OUT"
echo "  Ship it, then on that server:  sudo ./start.sh"
echo "  It appears on the key server as its own box: \"$LABEL\""
echo "================================================================"
