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

# Required env exported by CI
: "${REMOTE_BASE:?missing REMOTE_BASE}"
: "${DB_DIR:?missing DB_DIR}"
: "${SSH_USER:?missing SSH_USER}"
: "${SSH_HOST:?missing SSH_HOST}"
if [[ "${CI_RUNTIME_ENV_NAME:-prod}" != "devserver" ]]; then
  # Pass-through AppRole creds for the prod Vault Agent.
  : "${VAULT_ROLE_ID:?missing VAULT_ROLE_ID}"
  : "${VAULT_SECRET_ID:?missing VAULT_SECRET_ID}"
fi

REMOTE_DIR="${REMOTE_BASE%/}/${DB_DIR}"
REMOTE_TARGET="${SSH_USER}@${SSH_HOST}"
RUNTIME_ENV_FILE="${RUNTIME_ENV_FILE:-ci/prod/.env.runtime}"
COMPOSE_FILE="${DB_COMPOSE_FILE:-db.yml}"

# SSH options: quiet by default; add -vv in debug mode
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 options: quiet by default; add -v in debug mode
RSYNC_FLAGS=(-az --delete)
[[ "${DEBUG_DEPLOY:-0}" = "1" ]] && RSYNC_FLAGS=(-avz --delete)

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

# Sync compose bundle and runtime env to the remote host
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"

# Deploy on remote: pass AppRole creds ONLY to compose invocations.
# The vault-agent container writes them into tmpfs and unsets them internally.
ssh "${SSH_OPTS[@]}" "$REMOTE_TARGET" \
  REMOTE_DIR="$REMOTE_DIR" \
  COMPOSE_FILE="$COMPOSE_FILE" \
  VAULT_ROLE_ID="${VAULT_ROLE_ID:-}" \
  VAULT_SECRET_ID="${VAULT_SECRET_ID:-}" \
  bash -s <<'EOSSH'
set -euo pipefail
cd "${REMOTE_DIR}/compose"
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"
}
set -a
. ../env/.env.runtime
if [[ -f ../env/vault.env ]]; then
  load_kv_file ../env/vault.env
fi
set +a
COMPOSE_PROJECT_NAME="${DB_COMPOSE_PROJECT:-sendico-db}"
export COMPOSE_PROJECT_NAME
: "${VAULT_ADDR:?missing VAULT_ADDR}"
: "${VAULT_ROLE_ID:?missing VAULT_ROLE_ID}"
: "${VAULT_SECRET_ID:?missing VAULT_SECRET_ID}"

VAULT_ROLE_ID="${VAULT_ROLE_ID}" VAULT_SECRET_ID="${VAULT_SECRET_ID}" VAULT_ADDR="${VAULT_ADDR}" docker compose -f "${COMPOSE_FILE}" pull --quiet 2>/dev/null || \
VAULT_ROLE_ID="${VAULT_ROLE_ID}" VAULT_SECRET_ID="${VAULT_SECRET_ID}" VAULT_ADDR="${VAULT_ADDR}" docker compose -f "${COMPOSE_FILE}" pull

VAULT_ROLE_ID="${VAULT_ROLE_ID}" VAULT_SECRET_ID="${VAULT_SECRET_ID}" VAULT_ADDR="${VAULT_ADDR}" docker compose -f "${COMPOSE_FILE}" up -d --remove-orphans

docker compose -f "${COMPOSE_FILE}" ps
date -Is > .last_deploy
logger -t deploy-db "db deployed at $(date -Is) in ${REMOTE_DIR}"
EOSSH
