#!/bin/bash
#
# sbc-sanitize-identity — clear per-device identity before cloning an SD card.
#
# WHY THIS EXISTS: the VND-ID is the device's global identity for licensing,
# credit, sales, and the trial (one-per-device). It's generated ONCE at first
# boot from the chip serial + MAC, persisted to /etc/vendora/vnd_id, and then
# NEVER regenerated. A `dd` snapshot of a configured device carries that file —
# so every card flashed from the snapshot inherits the SOURCE device's identity
# and N physical boxes end up sharing one VND-ID (shared license, shared trial;
# see S34 / ADR-0015). Run this on a device BEFORE taking a `dd` snapshot that
# will be flashed onto OTHER boards, so each clone regenerates its OWN unique
# identity on first boot.
#
# Fresh `BUILD_MODE=production` Armbian images are already safe — the build
# never bakes a vnd_id. This tool is only for the "dd-clone-a-configured-box"
# workflow used for fast dev/test provisioning.
#
# Levels:
#   (default)  clear identity + license cache only. Your configured setup
#              (rates, network, customization, segments) is PRESERVED — the
#              clone keeps your config but regenerates its own VND-ID and
#              re-activates fresh against vendorawifi.com.
#   --full     default + wipe transactional data (vouchers, sales, coin events,
#              audit log, abuse counters, ESP grants) AND the wizard flag +
#              owner password, so each clone boots into first-run setup. Use
#              for a "golden master" you'll flash onto many fresh units.
#
# Usage:
#   sbc-sanitize-identity          # identity + license only
#   sbc-sanitize-identity --full   # + transactional data + fresh setup
#
# AFTER running: power OFF (do NOT reboot — a reboot regenerates the identity
# on THIS device, which a later snapshot would then carry), then dd the card:
#   sudo poweroff

set -euo pipefail

DB=/var/lib/vendora/state.db
VND_ID=/etc/vendora/vnd_id
MODE="${1:-identity}"
FULL=0

case "$MODE" in
    identity|--identity) FULL=0 ;;
    --full|full)         FULL=1 ;;
    -h|--help|help)
        cat <<'EOF'
sbc-sanitize-identity — clear per-device identity before cloning an SD card

Usage: sbc-sanitize-identity [--full]

  (default)  clear VND-ID + license cache only (config preserved)
  --full     + wipe vouchers/sales/coin events/audit/abuse/grants and the
             wizard flag + owner password (fresh-setup golden master)

Run BEFORE a `dd` snapshot meant for OTHER boards, so each clone regenerates
its own unique identity. Then `sudo poweroff` (do NOT reboot) and dd the card.
EOF
        exit 0 ;;
    *)
        echo "sbc-sanitize-identity: unknown option '$MODE'" >&2
        echo "usage: $0 [--full]   (try '$0 --help')" >&2
        exit 1 ;;
esac

echo "[sanitize] stopping vendora services…"
systemctl stop vendora-license vendora-portal vendora-admin \
    vendora-session vendora-api vendora-coin 2>/dev/null || true

OLD_ID="$(cat "$VND_ID" 2>/dev/null || echo '(none)')"
echo "[sanitize] removing device identity ($VND_ID)…"
echo "[sanitize]   was: $OLD_ID  → regenerates per-device on first boot"
rm -f "$VND_ID"

if [ -f "$DB" ]; then
    echo "[sanitize] resetting license cache…"
    sqlite3 "$DB" "DELETE FROM license_cache;" 2>/dev/null || true
    if [ "$FULL" = 1 ]; then
        echo "[sanitize] --full: wiping transactional data + setup state…"
        for t in vouchers sales_events coin_events audit_log abuse_throttle access_grants; do
            sqlite3 "$DB" "DELETE FROM $t;" 2>/dev/null || true
        done
        sqlite3 "$DB" \
            "DELETE FROM config WHERE key IN ('wizard_completed','owner_password_hash');" \
            2>/dev/null || true
    fi
else
    echo "[sanitize] WARN: $DB not found — skipping DB reset"
fi

echo
echo "[sanitize] DONE — this device's identity is cleared."
echo "[sanitize] NEXT: power off (do NOT reboot), then dd the SD card:"
echo "[sanitize]   sudo poweroff"
echo "[sanitize] Each card flashed from the snapshot generates its own VND-ID."
