#!/usr/bin/env bash
#
# Pull a live Awesomate site DOWN to a local directory (to start a Studio site
# from an existing live site). Read-only against live — it never changes the
# live site. Copies files + exports the live DB.
#
#   pull-live.sh --domain mysite.awesomate.site --to ~/Studio/mysite [--docroot PATH]
#
# Then import the files into a new WordPress Studio site and load db.sql.
# Client-side deps: bash, ssh, rsync, scp.
set -euo pipefail

CRED="$HOME/.awesomate/credentials.json"
[ -f "$CRED" ] || { echo "Not connected — run the Connect Claude Code setup from hub.awesomate.ai/claude first."; exit 1; }

DOMAIN="" TO="" DOCROOT=""
while [ "$#" -gt 0 ]; do
  case "$1" in
    --domain) DOMAIN="$2"; shift 2;;
    --to) TO="$2"; shift 2;;
    --docroot) DOCROOT="$2"; shift 2;;
    *) echo "Unknown option: $1"; exit 1;;
  esac
done
[ -n "$DOMAIN" ] && [ -n "$TO" ] || { echo "Usage: pull-live.sh --domain <live-domain> --to <local-dir> [--docroot PATH]"; exit 1; }
case "$DOMAIN" in *[!a-z0-9.-]*|"") echo "Invalid --domain."; exit 1;; esac

# Shared resolver: folder pin / AWESOMATE_ACCOUNT / sole profile → ssh block.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if ! CREDS_EVAL="$(node "$SCRIPT_DIR/resolve-account.mjs" --ssh)"; then
  exit 1
fi
eval "$CREDS_EVAL"
echo "→ account: $ACCT"

# Harden credentials-derived fields before they reach rsync/scp/ssh — rsync
# word-splits its -e remote-shell string, so whitespace here could inject ssh
# options (client RCE). Same gate as deploy.sh.
case "$P" in ''|*[!0-9]*) echo "Invalid ssh port in credentials."; exit 1;; esac
case "$H" in ''|*[!a-zA-Z0-9.-]*) echo "Invalid ssh host in credentials."; exit 1;; esac
case "$U" in ''|*[!a-z0-9]*) echo "Invalid ssh user in credentials."; exit 1;; esac
case "$K" in ''|*[[:space:]]*) echo "Invalid key path in credentials (whitespace not allowed)."; exit 1;; esac

DOCROOT="${DOCROOT:-/home/$U/public_html}"
mkdir -p "$TO"

echo "→ Pulling files from $U@$H:$DOCROOT …"
rsync -az -e "ssh -i $(printf %q "$K") -p $P -o StrictHostKeyChecking=accept-new -o BatchMode=yes" \
  --exclude '.deploy-import.sql' "$U@$H:$DOCROOT/" "$TO/"

echo "→ Exporting live database…"
ssh -i "$K" -p "$P" -o StrictHostKeyChecking=accept-new -o BatchMode=yes "$U@$H" \
  "cd $(printf %q "$DOCROOT") && wp db export /tmp/pull-live.sql --quiet"
scp -i "$K" -P "$P" -o StrictHostKeyChecking=accept-new -o BatchMode=yes "$U@$H:/tmp/pull-live.sql" "$TO/db.sql"
ssh -i "$K" -p "$P" -o StrictHostKeyChecking=accept-new -o BatchMode=yes "$U@$H" "rm -f /tmp/pull-live.sql"

echo "✓ Pulled to $TO (files + db.sql). Next: create a WordPress Studio site pointed at this folder and import db.sql."
