#!/usr/bin/env bash
set -euo pipefail
[[ "${DEBUG_DEPLOY:-0}" = "1" ]] && set -x
trap 'echo "[deploy-discovery] error at line $LINENO" >&2' ERR

: "${REMOTE_BASE:?missing REMOTE_BASE}"
: "${SSH_USER:?missing SSH_USER}"
: "${SSH_HOST:?missing SSH_HOST}"
: "${DISCOVERY_DIR:?missing DISCOVERY_DIR}"
: "${DISCOVERY_COMPOSE_PROJECT:?missing DISCOVERY_COMPOSE_PROJECT}"
: "${DISCOVERY_SERVICE_NAME:?missing DISCOVERY_SERVICE_NAME}"

REMOTE_DIR="${REMOTE_BASE%/}/${DISCOVERY_DIR}"
REMOTE_TARGET="${SSH_USER}@${SSH_HOST}"
RUNTIME_ENV_FILE="${RUNTIME_ENV_FILE:-ci/prod/.env.runtime}"
COMPOSE_FILE="discovery.yml"
SERVICE_NAMES="${DISCOVERY_SERVICE_NAME}"

REQUIRED_SECRETS=(
  NATS_USER
  NATS_PASSWORD
  NATS_URL
)

for var in "${REQUIRED_SECRETS[@]}"; do
  if [[ -z "${!var:-}" ]]; then
    echo "missing required secret env: ${var}" >&2
    exit 65
  fi
done

if [[ ! -s .env.version ]]; then
  echo ".env.version is missing; run version step first" >&2
  exit 66
fi

b64enc() {
  printf '%s' "$1" | base64 | tr -d '\n'
}

NATS_USER_B64="$(b64enc "${NATS_USER}")"
NATS_PASSWORD_B64="$(b64enc "${NATS_PASSWORD}")"
NATS_URL_B64="$(b64enc "${NATS_URL}")"

SSH_OPTS=(
  -i /root/.ssh/id_rsa
  -o StrictHostKeyChecking=no
  -o UserKnownHostsFile=/dev/null
  -o LogLevel=ERROR
  -o BatchMode=yes
  -o PreferredAuthentications=publickey
  -o ConnectTimeout=10
  -q
)
if [[ "${DEBUG_DEPLOY:-0}" = "1" ]]; then
  SSH_OPTS=("${SSH_OPTS[@]/-q/}" -vv)
fi

RSYNC_FLAGS=(-az --delete)
[[ "${DEBUG_DEPLOY:-0}" = "1" ]] && RSYNC_FLAGS=(-avz --delete)

ssh "${SSH_OPTS[@]}" "$REMOTE_TARGET" "mkdir -p ${REMOTE_DIR}/{compose,env}"

rsync "${RSYNC_FLAGS[@]}" -e "ssh ${SSH_OPTS[*]}" ci/prod/compose/ "$REMOTE_TARGET:${REMOTE_DIR}/compose/"
rsync "${RSYNC_FLAGS[@]}" -e "ssh ${SSH_OPTS[*]}" "${RUNTIME_ENV_FILE}" "$REMOTE_TARGET:${REMOTE_DIR}/env/.env.runtime"
rsync "${RSYNC_FLAGS[@]}" -e "ssh ${SSH_OPTS[*]}" .env.version         "$REMOTE_TARGET:${REMOTE_DIR}/env/.env.version"

SERVICES_LINE="${SERVICE_NAMES}"

ssh "${SSH_OPTS[@]}" "$REMOTE_TARGET" \
  REMOTE_DIR="$REMOTE_DIR" \
  COMPOSE_FILE="$COMPOSE_FILE" \
  COMPOSE_PROJECT="$DISCOVERY_COMPOSE_PROJECT" \
  SERVICES_LINE="$SERVICES_LINE" \
  NATS_USER_B64="$NATS_USER_B64" \
  NATS_PASSWORD_B64="$NATS_PASSWORD_B64" \
  NATS_URL_B64="$NATS_URL_B64" \
  bash -s <<'EOSSH'
set -euo pipefail
cd "${REMOTE_DIR}/compose"
set -a
. ../env/.env.runtime
load_kv_file() {
  local file="$1"
  while IFS= read -r line || [ -n "$line" ]; do
    case "$line" in
      ''|\#*) continue ;;
    esac
    if printf '%s' "$line" | grep -Eq '^[[:alpha:]_][[:alnum:]_]*='; then
      local key="${line%%=*}"
      local value="${line#*=}"
      key="$(printf '%s' "$key" | tr -d '[:space:]')"
      value="${value#"${value%%[![:space:]]*}"}"
      value="${value%"${value##*[![:space:]]}"}"
      if [[ -n "$key" ]]; then
        export "$key=$value"
      fi
    fi
  done <"$file"
}
load_kv_file ../env/.env.version
set +a

IMAGE_TAG="${IMAGE_TAG:-${APP_V}-${GIT_REV}}"
export IMAGE_TAG

if base64 -d >/dev/null 2>&1 <<<'AA=='; then
  BASE64_DECODE_FLAG='-d'
else
  BASE64_DECODE_FLAG='--decode'
fi

decode_b64() {
  val="$1"
  if [[ -z "$val" ]]; then
    printf ''
    return
  fi
  printf '%s' "$val" | base64 "${BASE64_DECODE_FLAG}"
}

NATS_USER="$(decode_b64 "$NATS_USER_B64")"
NATS_PASSWORD="$(decode_b64 "$NATS_PASSWORD_B64")"
NATS_URL="$(decode_b64 "$NATS_URL_B64")"

export NATS_USER NATS_PASSWORD NATS_URL
COMPOSE_PROJECT_NAME="$COMPOSE_PROJECT"
export COMPOSE_PROJECT_NAME
read -r -a SERVICES <<<"${SERVICES_LINE}"

pull_cmd=(docker compose -f "$COMPOSE_FILE" pull)
up_cmd=(docker compose -f "$COMPOSE_FILE" up -d --remove-orphans)
ps_cmd=(docker compose -f "$COMPOSE_FILE" ps)
if [[ "${#SERVICES[@]}" -gt 0 ]]; then
  pull_cmd+=("${SERVICES[@]}")
  up_cmd+=("${SERVICES[@]}")
  ps_cmd+=("${SERVICES[@]}")
fi

"${pull_cmd[@]}"
"${up_cmd[@]}"
"${ps_cmd[@]}"

date -Is > .last_deploy
logger -t "deploy-${COMPOSE_PROJECT_NAME}" "${COMPOSE_PROJECT_NAME} deployed at $(date -Is) in ${REMOTE_DIR}"
EOSSH
