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

: "${REMOTE_BASE:?missing REMOTE_BASE}"
: "${SSH_USER:?missing SSH_USER}"
: "${SSH_HOST:?missing SSH_HOST}"
: "${CHAIN_GATEWAY_DIR:?missing CHAIN_GATEWAY_DIR}"
: "${CHAIN_GATEWAY_COMPOSE_PROJECT:?missing CHAIN_GATEWAY_COMPOSE_PROJECT}"
: "${CHAIN_GATEWAY_SERVICE_NAME:?missing CHAIN_GATEWAY_SERVICE_NAME}"

REMOTE_DIR="${REMOTE_BASE%/}/${CHAIN_GATEWAY_DIR}"
REMOTE_TARGET="${SSH_USER}@${SSH_HOST}"
COMPOSE_FILE="chain_gateway.yml"
SERVICE_NAMES="${CHAIN_GATEWAY_SERVICE_NAME}"

REQUIRED_SECRETS=(
  CHAIN_GATEWAY_MONGO_USER
  CHAIN_GATEWAY_MONGO_PASSWORD
  CHAIN_GATEWAY_RPC_URL
  CHAIN_GATEWAY_SERVICE_WALLET_KEY
  CHAIN_GATEWAY_SERVICE_WALLET_ADDRESS
  CHAIN_GATEWAY_VAULT_ROLE_ID
  CHAIN_GATEWAY_VAULT_SECRET_ID
  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'
}

CHAIN_GATEWAY_MONGO_USER_B64="$(b64enc "${CHAIN_GATEWAY_MONGO_USER}")"
CHAIN_GATEWAY_MONGO_PASSWORD_B64="$(b64enc "${CHAIN_GATEWAY_MONGO_PASSWORD}")"
CHAIN_GATEWAY_RPC_URL_B64="$(b64enc "${CHAIN_GATEWAY_RPC_URL}")"
CHAIN_GATEWAY_SERVICE_WALLET_KEY_B64="$(b64enc "${CHAIN_GATEWAY_SERVICE_WALLET_KEY}")"
CHAIN_GATEWAY_SERVICE_WALLET_ADDRESS_B64="$(b64enc "${CHAIN_GATEWAY_SERVICE_WALLET_ADDRESS}")"
CHAIN_GATEWAY_VAULT_ROLE_ID_B64="$(b64enc "${CHAIN_GATEWAY_VAULT_ROLE_ID}")"
CHAIN_GATEWAY_VAULT_SECRET_ID_B64="$(b64enc "${CHAIN_GATEWAY_VAULT_SECRET_ID}")"
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
  -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/secrets ${REMOTE_DIR}/env"

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"
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="$CHAIN_GATEWAY_COMPOSE_PROJECT" \
  SERVICES_LINE="$SERVICES_LINE" \
  CHAIN_GATEWAY_MONGO_USER_B64="$CHAIN_GATEWAY_MONGO_USER_B64" \
  CHAIN_GATEWAY_MONGO_PASSWORD_B64="$CHAIN_GATEWAY_MONGO_PASSWORD_B64" \
  CHAIN_GATEWAY_RPC_URL_B64="$CHAIN_GATEWAY_RPC_URL_B64" \
  CHAIN_GATEWAY_SERVICE_WALLET_KEY_B64="$CHAIN_GATEWAY_SERVICE_WALLET_KEY_B64" \
  CHAIN_GATEWAY_SERVICE_WALLET_ADDRESS_B64="$CHAIN_GATEWAY_SERVICE_WALLET_ADDRESS_B64" \
  CHAIN_GATEWAY_VAULT_ROLE_ID_B64="$CHAIN_GATEWAY_VAULT_ROLE_ID_B64" \
  CHAIN_GATEWAY_VAULT_SECRET_ID_B64="$CHAIN_GATEWAY_VAULT_SECRET_ID_B64" \
  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

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}"
}

CHAIN_GATEWAY_MONGO_USER="$(decode_b64 "$CHAIN_GATEWAY_MONGO_USER_B64")"
CHAIN_GATEWAY_MONGO_PASSWORD="$(decode_b64 "$CHAIN_GATEWAY_MONGO_PASSWORD_B64")"
CHAIN_GATEWAY_RPC_URL="$(decode_b64 "$CHAIN_GATEWAY_RPC_URL_B64")"
CHAIN_GATEWAY_SERVICE_WALLET_KEY="$(decode_b64 "$CHAIN_GATEWAY_SERVICE_WALLET_KEY_B64")"
CHAIN_GATEWAY_SERVICE_WALLET_ADDRESS="$(decode_b64 "$CHAIN_GATEWAY_SERVICE_WALLET_ADDRESS_B64")"
CHAIN_GATEWAY_VAULT_ROLE_ID="$(decode_b64 "$CHAIN_GATEWAY_VAULT_ROLE_ID_B64")"
CHAIN_GATEWAY_VAULT_SECRET_ID="$(decode_b64 "$CHAIN_GATEWAY_VAULT_SECRET_ID_B64")"
NATS_USER="$(decode_b64 "$NATS_USER_B64")"
NATS_PASSWORD="$(decode_b64 "$NATS_PASSWORD_B64")"
NATS_URL="$(decode_b64 "$NATS_URL_B64")"

export CHAIN_GATEWAY_MONGO_USER CHAIN_GATEWAY_MONGO_PASSWORD
export CHAIN_GATEWAY_RPC_URL
export CHAIN_GATEWAY_SERVICE_WALLET_KEY CHAIN_GATEWAY_SERVICE_WALLET_ADDRESS
export CHAIN_GATEWAY_VAULT_ROLE_ID CHAIN_GATEWAY_VAULT_SECRET_ID
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
