#!/usr/bin/env bash
# Blue-green for core2 / console2 behind host Apache (UAT). Run as root from deploy/.
#   bluegreen.sh core|console deploy <tag>   start idle slot, health gate, flip, drain, stop old
#   bluegreen.sh core|console flip <port>    point Apache at a port (rollback while old side still runs)
#   bluegreen.sh core|console status
# KEEP_OLD=1 leaves the old side running (use for the first pm2 cutover).
# ponytail: no tag history / rollback command. Rollback = flip <old port>, or deploy <previous tag>.
set -euo pipefail

APP=${1:?core|console}; CMD=${2:?deploy|flip|status}; ARG=${3:-}
[[ $ARG =~ ^[A-Za-z0-9._-]*$ ]] || { echo "bad argument" >&2; exit 2; }
DIR=$(cd "$(dirname "$0")" && pwd)
CONF=/etc/apache2/conf-available/karma-upstreams.conf
DRAIN=${DRAIN:-45}

case $APP in
  core)    VAR=CORE2_PORT;    P=(9015 9016); OLD=9005; HOST=dev.core2.karmagroup.com;    URI=/health; OK='^200$';              F=compose.core.yml;    NAME=core2 ;;
  console) VAR=CONSOLE2_PORT; P=(3013 3014); OLD=3002; HOST=dev.console2.karmagroup.com; URI=/;       OK='^(200|30[0-9])$';  F=compose.console.yml; NAME=console2 ;;
  *) echo "unknown app" >&2; exit 2 ;;
esac

[ -f "$CONF" ] || { echo "missing $CONF" >&2; exit 1; }
exec 9>"/run/lock/bluegreen-$APP.lock"; flock -n 9 || { echo "another run in progress" >&2; exit 1; }
ACT=$(grep -oP "^Define $VAR \K[0-9]+" "$CONF")

code() { curl -s -o /dev/null --max-time 8 -w '%{http_code}' "$@" || true; }
slot() { [ "$1" = "${P[0]}" ] && echo a || echo b; }
dc()   { local s=$1 port=$2 tag=$3; shift 3; (cd "$DIR" && TAG=$tag SLOT=$s HOST_PORT=$port docker compose -p "$NAME-$s" -f "$F" "$@"); }

setport() {  # swap Apache upstream, verify via the public vhost, revert on failure
  cp "$CONF" "$CONF.prev"
  sed -i "s/^Define $VAR .*/Define $VAR $1/" "$CONF"
  if ! apachectl configtest 2>/dev/null; then cp "$CONF.prev" "$CONF"; echo "configtest failed, reverted" >&2; return 1; fi
  apachectl graceful; sleep 3
  [[ $(code --resolve "$HOST:443:127.0.0.1" "https://$HOST$URI") =~ $OK ]] && return 0
  cp "$CONF.prev" "$CONF"; apachectl graceful; echo "public check failed, reverted to $ACT" >&2; return 1
}

deploy() {
  local tag=$1 new s
  [ -n "$tag" ] || { echo "need tag" >&2; exit 2; }
  [ "$ACT" = "${P[0]}" ] && new=${P[1]} || new=${P[0]}
  s=$(slot "$new")
  docker image inspect "karma/$NAME:$tag" >/dev/null
  echo "active=$ACT -> new=$new (slot $s, tag $tag)"
  if ! dc "$s" "$new" "$tag" up -d --wait --wait-timeout 120 \
     || ! [[ $(code "http://127.0.0.1:$new$URI") =~ $OK ]]; then
    dc "$s" "$new" "$tag" down; echo "new slot unhealthy, traffic unchanged" >&2; exit 1
  fi
  setport "$new" || { dc "$s" "$new" "$tag" down; exit 1; }
  echo "traffic now on $new"
  if [ "${KEEP_OLD:-0}" = 1 ]; then echo "KEEP_OLD=1: old side on $ACT still running"; return; fi
  if [ "$ACT" = "${P[0]}" ] || [ "$ACT" = "${P[1]}" ]; then
    echo "draining old slot ${DRAIN}s"; sleep "$DRAIN"; dc "$(slot "$ACT")" "$ACT" x down
  else
    echo "old side is pm2 on $ACT: pm2 stop it after checks (stop, not delete)"
  fi
}

case $CMD in
  deploy) deploy "$ARG" ;;
  flip)   case " ${P[*]} $OLD " in
            *" $ARG "*) setport "$ARG" && echo "traffic now on $ARG" ;;
            *) echo "port must be one of: ${P[*]} $OLD" >&2; exit 2 ;;
          esac ;;
  status) echo "active port: $ACT"; docker ps --filter "name=$NAME-" --format '{{.Names}}  {{.Image}}  {{.Status}}  {{.Ports}}' ;;
  *) echo "unknown command" >&2; exit 2 ;;
esac
