#!/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}"
# Pass-through AppRole creds for Vault Agent (provided by Woodpecker secrets with existing names)
: "${VAULT_ROLE_ID:?missing VAULT_ROLE_ID}"
: "${VAULT_SECRET_ID:?missing VAULT_SECRET_ID}"

REMOTE_DIR="${REMOTE_BASE%/}/${DB_DIR}"
REMOTE_TARGET="${SSH_USER}@${SSH_HOST}"

# 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
  -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[*]}" ci/prod/.env.runtime "$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" \
  VAULT_ROLE_ID="$VAULT_ROLE_ID" \
  VAULT_SECRET_ID="$VAULT_SECRET_ID" \
  bash -s <<'EOSSH'
set -euo pipefail
cd "${REMOTE_DIR}/compose"
set -a; . ../env/.env.runtime; set +a
COMPOSE_PROJECT_NAME="${DB_COMPOSE_PROJECT:-sendico-db}"
export COMPOSE_PROJECT_NAME
# Run with ephemeral AppRole env (scoped only to these commands)
VAULT_ROLE_ID="${VAULT_ROLE_ID}" VAULT_SECRET_ID="${VAULT_SECRET_ID}" docker compose -f db.yml pull --quiet 2>/dev/null || \
VAULT_ROLE_ID="${VAULT_ROLE_ID}" VAULT_SECRET_ID="${VAULT_SECRET_ID}" docker compose -f db.yml pull

VAULT_ROLE_ID="${VAULT_ROLE_ID}" VAULT_SECRET_ID="${VAULT_SECRET_ID}" docker compose -f db.yml up -d --remove-orphans

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