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

: "${REMOTE_BASE:?missing REMOTE_BASE}"
: "${SSH_USER:?missing SSH_USER}"
: "${SSH_HOST:?missing SSH_HOST}"
: "${FRONTEND_DIR:?missing FRONTEND_DIR}"
: "${FRONTEND_COMPOSE_PROJECT:?missing FRONTEND_COMPOSE_PROJECT}"
: "${FRONTEND_SERVICE_NAME:?missing FRONTEND_SERVICE_NAME}"

REMOTE_DIR="${REMOTE_BASE%/}/${FRONTEND_DIR}"
REMOTE_TARGET="${SSH_USER}@${SSH_HOST}"
COMPOSE_FILE="frontend.yml"
SERVICE_NAMES="${FRONTEND_SERVICE_NAME}"

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

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,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="$FRONTEND_COMPOSE_PROJECT" \
  SERVICES_LINE="$SERVICES_LINE" \
  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

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
