#!/usr/bin/env bash
# manor-edge-install.sh — cross-platform (Linux + macOS terminal) MANOR edge
# installer. The Linux counterpart to ManorEdgeInstaller.command (the
# double-clickable macOS app): same key-then-handoff flow, but runs from a
# terminal on either OS. Downloaded from https://downloads.mymanor.click/
# manor-edge-install.sh (CDN) or https://mymanor.click/manor-edge-install.sh
# (committed fallback).
#
# Prompts for the single-use pairing key from your key link, then hands off to
# the server-generated install script
# (`curl .../pair/install/<key> | sudo MANOR_SELF_SERVE=1 bash`) — all the heavy
# lifting (Node install, setup-linux-edge.sh / macOS setup, services, pairing)
# lives server-side, not here. Keep this file SMALL.
#
# No key yet? Press Return with no key to submit an access request instead
# (POST /public/registrations) — the same flow as https://mymanor.click/register.
#
# Meant to be DOWNLOADED then run (`bash manor-edge-install.sh`), not
# curl-piped — it prompts on stdin. For a one-shot pipe use the universal
# one-liner from your key page instead:
#   curl -fsSL <apiBase>/pair/install/<KEY> | sudo MANOR_SELF_SERVE=1 bash
#
# ⚠ MUST STAY IN SYNC with ManorEdgeInstaller.command (macOS) in this same
# directory — the ADMIN_API, the request_access() body, the key validation, and
# the MANOR_SELF_SERVE=1 handoff are a shared contract. Change both together.

set -euo pipefail

ADMIN_API="https://0zdeqnboxi.execute-api.us-east-1.amazonaws.com/prod"

request_access() {
  echo ""
  echo "Request MANOR access — every request is reviewed by a human, and"
  echo "approval emails you a single-use key link."
  echo ""
  printf "Your name: "
  read -r NAME
  printf "Your email: "
  read -r EMAIL
  echo "Tier:"
  echo "  1. Standard  — shared cloud environment, fastest from approval to live"
  echo "  2. Dedicated — isolated AWS account just for your home (allow up to a day)"
  printf "Choose [1/2, default 1]: "
  read -r CHOICE
  TIER="shared"
  if [ "$CHOICE" = "2" ] || [ "$CHOICE" = "dedicated" ]; then TIER="dedicated"; fi
  ADDRESS=""
  if [ "$TIER" = "dedicated" ]; then
    printf "City / street address: "
    read -r ADDRESS
  fi
  if [ -z "$NAME" ] || [ -z "$EMAIL" ]; then
    echo "ERROR: name and email are required." >&2
    exit 2
  fi

  # Crude JSON hardening: drop quotes/backslashes rather than escape them.
  NAME="$(printf '%s' "$NAME" | tr -d '"\\')"
  EMAIL="$(printf '%s' "$EMAIL" | tr -d '"\\')"
  ADDRESS="$(printf '%s' "$ADDRESS" | tr -d '"\\')"

  BODY="{\"name\":\"$NAME\",\"email\":\"$EMAIL\",\"tier\":\"$TIER\",\"source\":\"installer\""
  if [ -n "$ADDRESS" ]; then BODY="$BODY,\"address\":\"$ADDRESS\""; fi
  BODY="$BODY}"

  RESP="$(curl -sS -X POST "$ADMIN_API/public/registrations" \
    -H 'Content-Type: application/json' --data "$BODY")" || {
    echo "ERROR: request failed — check your connection and try again." >&2
    exit 1
  }

  echo ""
  if printf '%s' "$RESP" | grep -q '"error"'; then
    echo "ERROR: the server rejected the request: $RESP" >&2
    exit 1
  elif printf '%s' "$RESP" | grep -q '"duplicate"'; then
    echo "You already have a request in review — approval lands by email."
  else
    echo "Request received. Watch $EMAIL for your approval and key link."
  fi
  echo "Track status any time at https://mymanor.click/register"
}

echo ""
echo "==================================================="
echo "  MANOR edge installer"
echo "==================================================="
echo ""

OS="$(uname -s)"
case "$OS" in
  Linux|Darwin) ;;
  *)
    echo "ERROR: unsupported operating system '$OS'." >&2
    echo "MANOR edge runs on macOS (13+) or Linux (Debian, Ubuntu, or" >&2
    echo "Raspberry Pi OS with systemd)." >&2
    exit 2
    ;;
esac

if ! command -v curl >/dev/null 2>&1; then
  if [ "$OS" = "Linux" ]; then
    echo "ERROR: curl not found — install it with 'sudo apt-get install -y curl' and retry." >&2
  else
    echo "ERROR: curl not found — install the Xcode command line tools and retry." >&2
  fi
  exit 2
fi

KEY="${1:-}"
if [ -z "$KEY" ]; then
  echo "Paste your MANOR pairing key (from your key link)."
  echo "No key yet? Just press Return to request access instead."
  printf "> "
  read -r KEY || KEY=""
fi
# Strip whitespace + lowercase so a padded copy-paste still validates.
KEY="$(printf '%s' "$KEY" | tr -d '[:space:]' | tr 'A-F' 'a-f')"

if [ -z "$KEY" ]; then
  request_access
  exit 0
fi

if ! printf '%s' "$KEY" | grep -Eq '^[a-f0-9]{32}$'; then
  echo "ERROR: that doesn't look like a MANOR pairing key (expected 32 hex characters)." >&2
  echo "Your key comes from the key link page at https://mymanor.click/edge-key" >&2
  exit 2
fi

echo ""
echo "Installing the MANOR edge — you'll be asked for your login password (sudo)."
echo "Keep this window open until it finishes."
echo ""

# Download to a temp file first, then run it as root with MANOR_SELF_SERVE=1 so
# the server-generated script auto-runs the platform bootstrap + setup +
# services-install finisher (a homeowner never sees a shell to run those by
# hand). We can't pipe `curl | sudo bash` and still carry the flag — sudo resets
# the environment by default — so set the var inline on the sudo command line,
# which sudo passes through to the script's environment.
TMP_SCRIPT="$(mktemp "${TMPDIR:-/tmp}/manor-edge-install.XXXXXX")"
trap 'rm -f "$TMP_SCRIPT"' EXIT
if ! curl -fsSL "$ADMIN_API/pair/install/$KEY" -o "$TMP_SCRIPT"; then
  echo "ERROR: failed to download the install script — check your connection and try again." >&2
  exit 1
fi
sudo MANOR_SELF_SERVE=1 bash "$TMP_SCRIPT"
