#!/usr/bin/env bash
# ============================================================
# Changemaker Control Panel — Setup Script
# ============================================================
# Detects the installation directory and configures .env with
# resolved absolute paths. Run once after cloning, or re-run
# any time you move the CCP directory.
#
# Usage:
#   cd changemaker-control-panel
#   chmod +x setup.sh
#   ./setup.sh
# ============================================================

set -euo pipefail

# ── Resolve absolute CCP directory ──────────────────────────
CCP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# ── Derive paths ────────────────────────────────────────────
INSTANCES_PATH="${CCP_DIR}/instances"
BACKUP_PATH="${CCP_DIR}/backups"

# Auto-detect CML source path (CCP is expected inside the CML repo)
CML_SOURCE="${CCP_DIR%/changemaker-control-panel}"
if [[ ! -f "${CML_SOURCE}/docker-compose.yml" ]]; then
  CML_SOURCE=""
fi

echo ""
echo "Changemaker Control Panel — Setup"
echo "=================================="
echo "  CCP directory:    ${CCP_DIR}"
echo "  Instances path:   ${INSTANCES_PATH}"
echo "  Backup path:      ${BACKUP_PATH}"
[[ -n "${CML_SOURCE}" ]] && echo "  CML source:       ${CML_SOURCE}"
echo ""

# ── Create directories ──────────────────────────────────────
mkdir -p "${INSTANCES_PATH}"
mkdir -p "${BACKUP_PATH}"
echo "✓ Created instance and backup directories"

# ── Create .env from .env.example if it doesn't exist ───────
if [[ ! -f "${CCP_DIR}/.env" ]]; then
  if [[ -f "${CCP_DIR}/.env.example" ]]; then
    cp "${CCP_DIR}/.env.example" "${CCP_DIR}/.env"
    echo "✓ Created .env from .env.example"
  else
    echo "⚠ No .env.example found — creating minimal .env"
    touch "${CCP_DIR}/.env"
  fi
fi

# ── Helper: set or update a key in .env ─────────────────────
update_env() {
  local key="$1" value="$2" file="${CCP_DIR}/.env"
  if grep -q "^${key}=" "$file" 2>/dev/null; then
    sed -i "s|^${key}=.*|${key}=${value}|" "$file"
  else
    echo "${key}=${value}" >> "$file"
  fi
}

# ── Set resolved paths ──────────────────────────────────────
update_env "INSTANCES_BASE_PATH" "${INSTANCES_PATH}"
update_env "BACKUP_STORAGE_PATH" "${BACKUP_PATH}"
[[ -n "${CML_SOURCE}" ]] && update_env "CML_SOURCE_PATH" "${CML_SOURCE}"
echo "✓ Updated .env with resolved absolute paths"

# ── Generate random secrets if still using placeholders ─────
generate_secret() {
  openssl rand -hex 32
}

for key in JWT_ACCESS_SECRET JWT_REFRESH_SECRET ENCRYPTION_KEY; do
  current=$(grep "^${key}=" "${CCP_DIR}/.env" 2>/dev/null | cut -d= -f2- || true)
  if [[ "$current" == *"change-me"* ]] || \
     [[ "$current" =~ ^[a]{32,}$ ]] || \
     [[ "$current" =~ ^[b]{32,}$ ]] || \
     [[ "$current" =~ ^[c]{32,}$ ]]; then
    update_env "$key" "$(generate_secret)"
    echo "✓ Generated random ${key}"
  fi
done

echo ""
echo "Setup complete! Next steps:"
echo "  1. Review ${CCP_DIR}/.env and adjust settings as needed"
echo "  2. Run: docker compose up -d"
echo ""
