#!/bin/bash
set -euo pipefail

# =============================================================================
# Deploy Vacations MCP to tbi-shared-mgmt via ArgoCD (manifest update)
#
# This script updates the deployment manifest in tbi-devops-common (shared branch)
# with the new image tag. ArgoCD auto-syncs the change to the cluster.
# =============================================================================

SERVICE_NAME="vacations-mcp"
MANIFEST_REPO="https://github.com/redlabelvacations/tbi-devops-common.git"
MANIFEST_BRANCH="shared"
MANIFEST_PATH="app/monitor/apps/vacations-mcp/deployment.yaml"
ECR_REGISTRY="495680544243.dkr.ecr.ca-central-1.amazonaws.com"
IMAGE_NAME="tbi-rlv-vacations-mcp"

# Read image tag
if [ -f "IMAGE_TAG" ]; then
  IMAGE_TAG=$(cat IMAGE_TAG | tr -d '[:space:]')
else
  echo "ERROR: IMAGE_TAG file not found"
  exit 1
fi

FULL_IMAGE="${ECR_REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG}"

echo "=== Deploying ${SERVICE_NAME} ==="
echo "Image: ${FULL_IMAGE}"
echo "Manifest: ${MANIFEST_PATH} on ${MANIFEST_BRANCH}"
echo ""

# --- Clone tbi-devops-common ---
echo "1. Cloning tbi-devops-common (${MANIFEST_BRANCH})..."
rm -rf /tmp/tbi-devops-common
# Authenticate via a credential helper (survives GitHub's redirect, unlike an
# inline token in the URL), and persist it on the clone so the later push works.
git -c credential.helper= \
    -c credential.helper='!f() { echo "username=x-access-token"; echo "password=${GITHUB_TOKEN}"; }; f' \
    clone "${MANIFEST_REPO}" /tmp/tbi-devops-common
git -C /tmp/tbi-devops-common config credential.helper '!f() { echo "username=x-access-token"; echo "password=${GITHUB_TOKEN}"; }; f'
cd /tmp/tbi-devops-common
git checkout "${MANIFEST_BRANCH}"

# --- Update image tag in deployment manifest ---
echo "2. Updating image tag in ${MANIFEST_PATH}..."
if [ ! -f "${MANIFEST_PATH}" ]; then
  echo "ERROR: Manifest file not found: ${MANIFEST_PATH}"
  exit 1
fi

sed -i "s|image: .*${IMAGE_NAME}:.*|image: ${FULL_IMAGE}|" "${MANIFEST_PATH}"

# --- Also update cronjob image tag ---
CRONJOB_PATH="app/monitor/apps/vacations-mcp/cronjob.yaml"
if [ -f "${CRONJOB_PATH}" ]; then
  sed -i "s|image: .*${IMAGE_NAME}:.*|image: ${FULL_IMAGE}|" "${CRONJOB_PATH}"
  echo "   Updated cronjob: ${CRONJOB_PATH}"
fi

echo "   Updated to: ${FULL_IMAGE}"

# --- Commit and push ---
echo "3. Committing and pushing..."
git config user.name "CircleCI Bot"
git config user.email "circleci@tbidevelopment.ca"

git add "${MANIFEST_PATH}"
git add "${CRONJOB_PATH}" 2>/dev/null || true

if git diff --cached --quiet; then
  echo "   No changes detected — image tag already up to date"
else
  git commit -m "Update ${SERVICE_NAME} image to ${IMAGE_TAG}

Deployed by CircleCI build #${CIRCLE_BUILD_NUM:-unknown}
Branch: ${CIRCLE_BRANCH:-unknown}
Commit: ${CIRCLE_SHA1:-unknown}"

  # Retry push with rebase on conflict
  MAX_RETRIES=5
  ATTEMPT=1
  while [ $ATTEMPT -le $MAX_RETRIES ]; do
    if git push origin "${MANIFEST_BRANCH}" 2>&1; then
      echo "   ✓ Pushed to ${MANIFEST_BRANCH}"
      break
    fi
    echo "   Push failed (attempt ${ATTEMPT}/${MAX_RETRIES}), rebasing and retrying..."
    git pull --rebase origin "${MANIFEST_BRANCH}"
    ATTEMPT=$((ATTEMPT + 1))
  done

  if [ $ATTEMPT -gt $MAX_RETRIES ]; then
    echo "ERROR: Failed to push after ${MAX_RETRIES} attempts"
    exit 1
  fi
fi

echo ""
echo "=== Deploy Complete ==="
echo "ArgoCD will auto-sync the updated manifest to tbi-shared-mgmt."
echo "Monitor: ArgoCD UI → Applications → vacations-mcp"
