#!/usr/bin/env bash
# Deploy explorer config (token list, networks) to VMID 5000 for /api/config/* endpoints.
# Run from repo root. Requires Proxmox host access (pct exec) or SSH to explorer container.
#
# Usage:
#   From Proxmox host:  pct exec 5000 -- bash -c 'mkdir -p /var/www/html/config'
#   Then: ./scripts/deploy-explorer-config-to-vmid5000.sh
#
# Or run inside VMID 5000:
#   pct push 5000 /path/to/DUAL_CHAIN_TOKEN_LIST.tokenlist.json /var/www/html/config/
#   pct push 5000 /path/to/DUAL_CHAIN_NETWORKS.json /var/www/html/config/

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
CONFIG_SRC="$REPO_ROOT/explorer-monorepo/backend/api/rest/config/metamask"
VMID="${EXPLORER_VMID:-5000}"
PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.12}"
EXEC_MODE="${EXEC_MODE:-pct}"

if [ ! -f "$CONFIG_SRC/DUAL_CHAIN_TOKEN_LIST.tokenlist.json" ]; then
  echo "Error: Token list not found at $CONFIG_SRC/DUAL_CHAIN_TOKEN_LIST.tokenlist.json" >&2
  exit 1
fi
if [ ! -f "$CONFIG_SRC/DUAL_CHAIN_NETWORKS.json" ]; then
  echo "Error: Networks config not found at $CONFIG_SRC/DUAL_CHAIN_NETWORKS.json" >&2
  exit 1
fi

echo "Deploying explorer config to VMID $VMID..."
echo "  Token list: $CONFIG_SRC/DUAL_CHAIN_TOKEN_LIST.tokenlist.json"
echo "  Networks:   $CONFIG_SRC/DUAL_CHAIN_NETWORKS.json"
echo ""

case "$EXEC_MODE" in
  pct)
    if command -v pct &>/dev/null; then
      pct exec "$VMID" -- mkdir -p /var/www/html/config
      pct push "$VMID" "$CONFIG_SRC/DUAL_CHAIN_TOKEN_LIST.tokenlist.json" /var/www/html/config/DUAL_CHAIN_TOKEN_LIST.tokenlist.json
      pct push "$VMID" "$CONFIG_SRC/DUAL_CHAIN_NETWORKS.json" /var/www/html/config/DUAL_CHAIN_NETWORKS.json
      echo "Done. Verify: curl -s https://explorer.d-bis.org/api/config/token-list | jq '.tokens | length'"
    else
      echo "pct not available. Use EXEC_MODE=ssh or run manually inside VMID 5000:"
      echo "  mkdir -p /var/www/html/config"
      echo "  # Copy DUAL_CHAIN_TOKEN_LIST.tokenlist.json and DUAL_CHAIN_NETWORKS.json to /var/www/html/config/"
      exit 1
    fi
    ;;
  ssh)
    CONTAINER_IP="${EXPLORER_IP:-192.168.11.140}"
    TMP_DIR=$(mktemp -d)
    trap "rm -rf $TMP_DIR" EXIT
    cp "$CONFIG_SRC/DUAL_CHAIN_TOKEN_LIST.tokenlist.json" "$TMP_DIR/"
    cp "$CONFIG_SRC/DUAL_CHAIN_NETWORKS.json" "$TMP_DIR/"
    scp "$TMP_DIR/DUAL_CHAIN_TOKEN_LIST.tokenlist.json" "root@$CONTAINER_IP:/var/www/html/config/" 2>/dev/null || {
      echo "SSH to $CONTAINER_IP failed. Ensure config dir exists: ssh root@$CONTAINER_IP 'mkdir -p /var/www/html/config'"
      exit 1
    }
    scp "$TMP_DIR/DUAL_CHAIN_NETWORKS.json" "root@$CONTAINER_IP:/var/www/html/config/"
    echo "Done. Verify: curl -s https://explorer.d-bis.org/api/config/token-list | jq '.tokens | length'"
    ;;
  *)
    echo "Unknown EXEC_MODE=$EXEC_MODE. Use pct or ssh." >&2
    exit 1
    ;;
esac
