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

: "${REMOTE_BASE:?missing REMOTE_BASE}"
: "${NATS_DIR:?missing NATS_DIR}"
: "${SSH_USER:?missing SSH_USER}"
: "${SSH_HOST:?missing SSH_HOST}"
: "${NATS_USER:?missing NATS_USER}"
: "${NATS_PASSWORD:?missing NATS_PASSWORD}"

REMOTE_DIR="${REMOTE_BASE%/}/${NATS_DIR}"
REMOTE_TARGET="${SSH_USER}@${SSH_HOST}"
RUNTIME_ENV_FILE="${RUNTIME_ENV_FILE:-ci/prod/.env.runtime}"

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/nats.yml "$REMOTE_TARGET:${REMOTE_DIR}/compose/nats.yml"
rsync "${RSYNC_FLAGS[@]}" -e "ssh ${SSH_OPTS[*]}" ci/prod/compose/nats.dockerfile "$REMOTE_TARGET:${REMOTE_DIR}/compose/nats.dockerfile"
rsync "${RSYNC_FLAGS[@]}" -e "ssh ${SSH_OPTS[*]}" "${RUNTIME_ENV_FILE}" "$REMOTE_TARGET:${REMOTE_DIR}/env/.env.runtime"

ssh "${SSH_OPTS[@]}" "$REMOTE_TARGET" \
  REMOTE_DIR="$REMOTE_DIR" \
  NATS_USER="$NATS_USER" \
  NATS_PASSWORD="$NATS_PASSWORD" \
  bash -s <<'EOSSH'
set -euo pipefail
cd "${REMOTE_DIR}/compose"
set -a; . ../env/.env.runtime; set +a
: "${NATS_COMPOSE_PROJECT:=sendico-nats}"
: "${NATS_USER:?missing NATS_USER}"
: "${NATS_PASSWORD:?missing NATS_PASSWORD}"
COMPOSE_PROJECT_NAME="$NATS_COMPOSE_PROJECT"
export COMPOSE_PROJECT_NAME
export NATS_USER NATS_PASSWORD

docker compose -f nats.yml pull --quiet 2>/dev/null || docker compose -f nats.yml pull
docker compose -f nats.yml build sendico_nats
docker compose -f nats.yml up -d --remove-orphans

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