#!/bin/bash
set -euo pipefail

PINK_BOLD='\033[1;38;2;255;105;180m'
RESET='\033[0m'

print_banner() {
  echo ""
  echo -e "${PINK_BOLD}   ██████╗  █████╗ ██████╗ ██████╗ ███████╗███╗   ██╗${RESET}"
  echo -e "${PINK_BOLD}  ██╔════╝ ██╔══██╗██╔══██╗██╔══██╗██╔════╝████╗  ██║${RESET}"
  echo -e "${PINK_BOLD}  ██║  ███╗███████║██████╔╝██║  ██║█████╗  ██╔██╗ ██║${RESET}"
  echo -e "${PINK_BOLD}  ██║   ██║██╔══██║██╔══██╗██║  ██║██╔══╝  ██║╚██╗██║${RESET}"
  echo -e "${PINK_BOLD}  ╚██████╔╝██║  ██║██║  ██║██████╔╝███████╗██║ ╚████║${RESET}"
  echo -e "${PINK_BOLD}   ╚═════╝ ╚═╝  ╚═╝╚═╝  ╚═╝╚═════╝ ╚══════╝╚═╝  ╚═══╝${RESET}"
  echo ""
}

print_banner

BASE_URL="https://solverup.garden.finance/main/scripts/solver-dashboardup"
INSTALL_DIR="solver-dashboardup"
BASE_DIR="$HOME/.solver-dashboard"
API_KEY_WRITE_FILE="$BASE_DIR/api_key.txt"

SCRIPTS=(
  caddy.sh
  cdn.sh
  config.sh
  core.sh
  dependencies.sh
  download.sh
  frontend.sh
  install.sh
  migration.sh
  service.sh
  solver-dashboardup.sh
  utils.sh
  version.sh
)

log() { echo "[INFO] $1"; }
err() { echo "[ERROR] $1" >&2; exit 1; }

# Parse arguments — blob can appear before or after --only-install
ONLY_INSTALL=false
ENC_BLOB=""
for arg in "$@"; do
  case "$arg" in
    --only-install) ONLY_INSTALL=true ;;
    --*) ;;  # ignore other flags
    *) [ -z "$ENC_BLOB" ] && ENC_BLOB="$arg" ;;
  esac
done
[ -z "$ENC_BLOB" ] && err "Encrypted blob missing. Usage: ./install.sh [--only-install] <Base64-blob>"

# Downloader
if command -v curl >/dev/null 2>&1; then
  DL="curl -fsSL -o"
else
  err "curl is required"
fi

# Fetch and source the ECR auth helpers
ECR_AUTH_TMP="$(mktemp)"
curl -fsSL "https://solverup.garden.finance/main/scripts/ecr-auth.sh" -o "$ECR_AUTH_TMP" \
  || err "Failed to download ecr-auth.sh"
# shellcheck source=/dev/null
source "$ECR_AUTH_TMP"

# Detect OS
OS="$(uname -s)"
case "$OS" in
  Linux*)   OS_TYPE="linux" ;;
  Darwin*)  OS_TYPE="mac" ;;
  *)        err "Unsupported OS: $OS" ;;
esac

# Docker check
check_docker_running() { docker info >/dev/null 2>&1; }

if command -v docker >/dev/null 2>&1; then
  log "Docker is installed"
  if ! check_docker_running; then
    log "Docker not running, attempting start..."
    if [ "$OS_TYPE" = "linux" ]; then
      sudo systemctl start docker 2>/dev/null || sudo service docker start 2>/dev/null || err "Failed to start Docker"
    elif [ "$OS_TYPE" = "mac" ]; then
      open -a Docker 2>/dev/null || err "Start Docker Desktop manually"
      sleep 5
    fi
  fi
else
  log "Docker not installed"
  if [ "$OS_TYPE" = "linux" ]; then
    log "Installing Docker..."
    curl -fsSL https://get.docker.com -o get-docker.sh
    sh get-docker.sh || err "Failed to install Docker"
    rm -f get-docker.sh
    sudo usermod -aG docker "$USER"
  else
    err "Install Docker Desktop on macOS and rerun"
  fi
fi

# Docker Compose check
if docker compose version >/dev/null 2>&1 || docker-compose version >/dev/null 2>&1; then
  log "Docker Compose available"
else
  err "Docker Compose missing"
fi

# Decode compressed credentials blob (aws_key::aws_secret::ecr_url::api_key)
log "Decoding compressed credentials blob..."
DECODED=$(printf '%s' "$ENC_BLOB" | base64 --decode | zstd -d -q -c) || err "Failed to decode blob"
parse_blob "$DECODED" || err "Decoded blob missing AWS key/secret or ECR registry URL"
API_KEY="$BLOB_API_KEY"
log "Configured ECR registry: $BLOB_ECR_URL"

# Save blob for future updates
mkdir -p "$BASE_DIR"
echo "$ENC_BLOB" > "$BASE_DIR/installer_blob"
chmod 600 "$BASE_DIR/installer_blob"
log "Saved installer blob for future updates"

# Fetch and save current versions (only on first install)
if [ ! -f "$BASE_DIR/current_dashboard_version" ]; then
  log "Fetching and saving dashboard version..."
  DASHBOARD_VERSION=$(curl -s http://gos.btcfi.wtf/solver-dashboard-updater.json | grep -o '"version"[[:space:]]*:[[:space:]]*"[^"]*"' | head -1 | grep -o '"[^"]*"$' | tr -d '"' || echo "unknown")
  [ -z "$DASHBOARD_VERSION" ] && DASHBOARD_VERSION="unknown"
  echo "$DASHBOARD_VERSION" > "$BASE_DIR/current_dashboard_version"
  log "Saved dashboard version: $DASHBOARD_VERSION"
fi

if [ ! -f "$BASE_DIR/current_solverd_version" ]; then
  log "Fetching and saving solverd version..."
  SOLVERD_VERSION=$(curl -s http://gos.btcfi.wtf/solverd-updater.json | grep -o '"version"[[:space:]]*:[[:space:]]*"[^"]*"' | head -1 | grep -o '"[^"]*"$' | tr -d '"' || echo "unknown")
  [ -z "$SOLVERD_VERSION" ] && SOLVERD_VERSION="unknown"
  echo "$SOLVERD_VERSION" > "$BASE_DIR/current_solverd_version"
  log "Saved solverd version: $SOLVERD_VERSION"
fi

# Configure AWS ECR authentication (replaces the old registry credential login)
log "Configuring AWS ECR authentication..."
setup_ecr_auth "$BLOB_AWS_KEY" "$BLOB_AWS_SECRET" "$BLOB_ECR_URL" || err "Failed to configure ECR authentication"
export REGISTRY_URL="$BLOB_ECR_URL"
echo "$BLOB_ECR_URL" > "$BASE_DIR/registry_url"


# Backup .solverd directory before installation if it exists
SOURCE_DIR="$HOME/.solverd"
if [ -d "$SOURCE_DIR" ]; then
  log "Backing up .solverd directory before installation"
  # Generate timestamp in format: YYYYMMDD-HHMMSS (filesystem-safe)
  TIMESTAMP=$(date '+%Y%m%d-%H%M%S')
  BACKUP_BASE_DIR="$HOME/.solverd-backups"
  BACKUP_DIR="${BACKUP_BASE_DIR}/.solverd-${TIMESTAMP}"

  log "Copying $SOURCE_DIR to $BACKUP_DIR"
  mkdir -p "$BACKUP_DIR"

  # Copy the directory
  if cp -a "$SOURCE_DIR/." "$BACKUP_DIR/"; then
    log "Successfully backed up $SOURCE_DIR to $BACKUP_DIR"
  else
    log "Warning: Failed to backup $SOURCE_DIR, continuing with installation"
  fi

  log "solverd backup completed to $BACKUP_DIR"
else
  log ".solverd directory does not exist, skipping backup"
fi

# Install solverd if missing
log "installing solverd..."
curl -fsSL https://solverup.garden.finance/main/scripts/solverdup.sh | ONLY_INSTALL="$ONLY_INSTALL" bash -s -- "$ENC_BLOB" || err "Failed to install solverd"
log "solverd installed successfully"

# Create working directory
mkdir -p "$INSTALL_DIR"
cd "$INSTALL_DIR"

log "Downloading dashboard scripts into $(pwd)..."
for file in "${SCRIPTS[@]}"; do
  url="$BASE_URL/$file"
  log "Downloading $url"
  $DL "$file" "$url" || err "Failed to download $file"
  chmod +x "$file"
done

# Ensure entrypoint exists
[ -f solver-dashboardup.sh ] || err "solver-dashboardup.sh missing"

mkdir -p "$BASE_DIR"
touch "$BASE_DIR/solver-dashboardup.log"

# Only removes the version lock and old binary — logs, api_key, and caddy config are kept.
if [ -f "$BASE_DIR/version.lock" ] || [ -d "$BASE_DIR/solver-dashboard" ]; then
  log "Clearing previous install state for clean installation..."
  rm -f "$BASE_DIR/version.lock"
  rm -rf "$BASE_DIR/solver-dashboard"
  log "Previous install state cleared"
fi

# Run main script
START_FAILED=0
if ! ONLY_INSTALL="$ONLY_INSTALL" ./solver-dashboardup.sh --start; then
  START_FAILED=1
fi

if [ "$START_FAILED" -ne 0 ]; then
  log "Failed to start solver-dashboardup, retrying with sudo..."
  if ! sudo HOME="$HOME" ONLY_INSTALL="$ONLY_INSTALL" ./solver-dashboardup.sh --start; then
    err "sudo also failed to start solver-dashboardup. Check logs."
  else
    log "solver-dashboardup started successfully using sudo."
  fi
fi

# Wait for services to be ready
log "Waiting for frontend container and backend to be ready..."
sleep 5

# Setup Caddy reverse proxy
log "Setting up Caddy reverse proxy..."

CADDY_CONTAINER_NAME="solver-dashboard-caddy"
CADDY_IMAGE="caddy:2"
CADDY_BASE_DIR="$BASE_DIR/caddy"
CADDYFILE_PATH="$CADDY_BASE_DIR/Caddyfile"

# Create Caddy directories
mkdir -p "$CADDY_BASE_DIR/data"
mkdir -p "$CADDY_BASE_DIR/config"
mkdir -p "$CADDY_BASE_DIR/static"

# Determine backend and frontend hosts based on OS
if [ "$OS_TYPE" = "linux" ]; then
  BACKEND_HOST="localhost:8080"
  FRONTEND_HOST="localhost:3000"
  NETWORK_ARG="--network host"
else
  BACKEND_HOST="host.docker.internal:8080"
  FRONTEND_HOST="host.docker.internal:3000"
  NETWORK_ARG="--add-host=host.docker.internal:host-gateway"
fi

# Copy static maintenance page
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
if [ -f "$SCRIPT_DIR/maintenance.html" ]; then
  cp "$SCRIPT_DIR/maintenance.html" "$CADDY_BASE_DIR/static/maintenance.html"
  log "Copied maintenance.html to Caddy static directory"
elif curl -sSfL "https://solverup.garden.finance/main/static/maintenance.html" -o "$CADDY_BASE_DIR/static/maintenance.html" 2>/dev/null; then
  log "Downloaded maintenance.html from CDN"
else
  err "maintenance.html not found in scripts directory and could not be downloaded"
fi

# Create Caddyfile with error handlers
cat > "$CADDYFILE_PATH" << EOF
:${CADDY_PORT:-80} {
    # Serve static maintenance page on backend errors (502, 503)
    handle_errors 502 503 {
        root * /srv/static
        rewrite * /maintenance.html
        file_server
    }

    # Proxy API requests (strip /api prefix)
    handle /api/* {
        uri strip_prefix /api
        reverse_proxy ${BACKEND_HOST} {
            health_uri /health
            health_interval 10s
            health_timeout 5s
        }
    }

    # Proxy all other requests to frontend
    reverse_proxy ${FRONTEND_HOST} {
        health_uri /
        health_interval 10s
        health_timeout 5s
    }
}
EOF

log "Caddyfile created successfully"

# If Caddy is already running — reload config in-place, never stop it
# If not running — do a fresh start
if docker ps --format '{{.Names}}' 2>/dev/null | grep -q "^${CADDY_CONTAINER_NAME}$"; then
  log "Caddy is already running. Reloading config in-place..."
  if docker exec "${CADDY_CONTAINER_NAME}" caddy reload --config /etc/caddy/Caddyfile --force >/dev/null 2>&1; then
    log "Caddy config reloaded successfully"
  else
    log "Warning: Caddy reload failed, attempting restart..."
    docker restart "${CADDY_CONTAINER_NAME}" >/dev/null 2>&1 || true
  fi
else
  # Container exists but is stopped — remove and do fresh start
  if docker ps -a --format '{{.Names}}' 2>/dev/null | grep -q "^${CADDY_CONTAINER_NAME}$"; then
    log "Removing stopped Caddy container..."
    docker rm "${CADDY_CONTAINER_NAME}" >/dev/null 2>&1 || true
  fi

  # Pull Caddy image
  log "Pulling Caddy image: ${CADDY_IMAGE}"
  if ! docker pull "${CADDY_IMAGE}" >/dev/null 2>&1; then
    log "Warning: Failed to pull Caddy image, but continuing..."
  fi

  # Start Caddy container
  log "Starting Caddy container: ${CADDY_CONTAINER_NAME}"
  if docker run -d \
      --name "${CADDY_CONTAINER_NAME}" \
      --restart unless-stopped \
      -p "${CADDY_PORT:-80}:${CADDY_PORT:-80}" \
      -p 443:443 \
      -v "${CADDYFILE_PATH}:/etc/caddy/Caddyfile:ro" \
      -v "${CADDY_BASE_DIR}/data:/data" \
      -v "${CADDY_BASE_DIR}/config:/config" \
      -v "${CADDY_BASE_DIR}/static:/srv/static:ro" \
      ${NETWORK_ARG} \
      "${CADDY_IMAGE}" >/dev/null 2>&1; then
    log "Caddy container started successfully"
    log "Caddy is now proxying:"
    log "  - Frontend: http://localhost (port ${CADDY_PORT:-80})"
    log "  - Backend API: http://localhost/api/* -> ${BACKEND_HOST}"
  else
    log "Warning: Failed to start Caddy container, but continuing installation..."
    if [ "$OS_TYPE" = "linux" ]; then
      log "Attempting to start Caddy with sudo..."
      if sudo docker run -d \
          --name "${CADDY_CONTAINER_NAME}" \
          --restart unless-stopped \
          -p "${CADDY_PORT:-80}:${CADDY_PORT:-80}" \
          -p 443:443 \
          -v "${CADDYFILE_PATH}:/etc/caddy/Caddyfile:ro" \
          -v "${CADDY_BASE_DIR}/data:/data" \
          -v "${CADDY_BASE_DIR}/config:/config" \
          -v "${CADDY_BASE_DIR}/static:/srv/static:ro" \
          ${NETWORK_ARG} \
          "${CADDY_IMAGE}" >/dev/null 2>&1; then
        log "Caddy container started successfully with sudo"
      else
        log "Warning: Caddy container failed to start even with sudo. You may need to start it manually."
      fi
    fi
  fi
fi

# Verify Caddy is running
sleep 2
if docker ps --format '{{.Names}}' 2>/dev/null | grep -q "^${CADDY_CONTAINER_NAME}$"; then
  log "✓ Caddy container is running and ready"
else
  log "Warning: Caddy container may not be running. Check with: docker ps -a | grep ${CADDY_CONTAINER_NAME}"
fi

echo "$API_KEY" > "$API_KEY_WRITE_FILE"
log "Setup completed successfully ✅"

PUBLIC_IP=$(curl -fsSL https://api.ipify.org 2>/dev/null || curl -fsSL https://ifconfig.me 2>/dev/null || echo "")
if [ -n "$PUBLIC_IP" ]; then
  log ""
  log "To attach a domain to your solver, please add this A record in your domain DNS provider:"
  log "  A record: @ -> $PUBLIC_IP"
  log ""
else
  log ""
  log "To attach a domain to your solver, please add an A record in your domain DNS provider"
  log "  pointing to this server's public IP address."
  log ""
fi
