#!/bin/bash
# deploy-freshcloud-mail.sh
# Deploy avidtech6/freshcloud-mail to /var/www/freshvibeapps/clients/_vendors/
# and symlink it into oscar-platform/api/email.
#
# Usage:  bash pact/scripts/deploy-freshcloud-mail.sh
# Pre-reqs: GITHUB_PAT_FG_1 or GITHUB_TOKEN in env (fine-grained PAT, repo scope)
#           SSH access to VPS (185.249.73.178 as root with kbf544r26 — stored in
#           operator's vault, NOT in this script)
#
# Idempotent — safe to re-run. Backs up any existing deploy.
set -euo pipefail

REPO="https://github.com/avidtech6/freshcloud-mail.git"
VENDOR_DIR="/var/www/freshvibeapps/clients/_vendors/freshcloud-mail"
TARGET_SYMLINK="/var/www/freshvibeapps/clients/oscar-platform/api/email"
SSH_HOST="185.249.73.178"
SSH_USER="root"

# Get the token (from env or operator panel vault)
TOKEN="${GITHUB_PAT_FG_1:-${GITHUB_TOKEN:-}}"
if [ -z "$TOKEN" ]; then
  echo "✗ No GITHUB_PAT_FG_1 or GITHUB_TOKEN in env. Cannot clone private repo."
  echo "  Either set the env var, or pre-populate the vendor dir on the VPS."
  exit 1
fi

echo "→ Deploying avidtech6/freshcloud-mail to ${VENDOR_DIR}"
echo "  Repo: ${REPO}"
echo

# Step 1: Clone or pull on VPS
echo "→ [1/4] Cloning/updating repo on VPS (depth 1, fresh data)..."
ssh -o StrictHostKeyChecking=no "${SSH_USER}@${SSH_HOST}" "
  set -e
  if [ -d '${VENDOR_DIR}/.git' ]; then
    echo '  Existing clone found, fetching latest (depth 1)...'
    cd '${VENDOR_DIR}'
    git fetch --depth 1 origin main
    git reset --hard origin/main
  else
    echo '  No existing clone, creating (depth 1)...'
    mkdir -p '\$(dirname ${VENDOR_DIR})'
    git clone --depth 1 '${REPO/\/\//\/\/avidtech6:${TOKEN}@}' '${VENDOR_DIR}'
  fi
  chown -R www-data:www-data '${VENDOR_DIR}'
"

# Step 2: Symlink in Oscar's app dir
echo "→ [2/4] Ensuring symlink ${TARGET_SYMLINK} → ${VENDOR_DIR}/api/email"
ssh -o StrictHostKeyChecking=no "${SSH_USER}@${SSH_HOST}" "
  set -e
  if [ -L '${TARGET_SYMLINK}' ]; then
    echo '  Symlink already exists, verifying target...'
    current=\$(readlink '${TARGET_SYMLINK}')
    if [ \"\${current}\" != '${VENDOR_DIR}/api/email' ]; then
      echo \"  Symlink points to \${current}, updating to ${VENDOR_DIR}/api/email\"
      rm '${TARGET_SYMLINK}'
      ln -s '${VENDOR_DIR}/api/email' '${TARGET_SYMLINK}'
    fi
  elif [ -d '${TARGET_SYMLINK}' ]; then
    echo '  Existing directory, backing up to .bak-pre-symlink-TS...'
    mv '${TARGET_SYMLINK}' '${TARGET_SYMLINK}.bak-pre-symlink-\$(date +%Y%m%d-%H%M%S)'
    ln -s '${VENDOR_DIR}/api/email' '${TARGET_SYMLINK}'
  else
    ln -s '${VENDOR_DIR}/api/email' '${TARGET_SYMLINK}'
  fi
  chown -h www-data:www-data '${TARGET_SYMLINK}'
"

# Step 3: Test the endpoint
echo "→ [3/4] Testing endpoint..."
TEST_URL="https://oscar-platform.freshvibeapps.com/api/email/health"
echo "  GET ${TEST_URL}"
HEALTH=$(curl -sL "${TEST_URL}")
echo "  Response: ${HEALTH}"

if echo "${HEALTH}" | grep -q '"status": "ok"'; then
  echo "  ✓ Health check passed"
else
  echo "  ✗ Health check failed"
  exit 1
fi

# Step 4: Show summary
echo
echo "→ [4/4] Summary"
echo "  Repo:      ${REPO}"
echo "  VPS path:  ${VENDOR_DIR}"
echo "  Symlink:   ${TARGET_SYMLINK}"
echo "  Live URL:  https://oscar-platform.freshvibeapps.com/api/email/"
echo
echo "✓ Deploy complete"
