#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

REMOTE_HOST="${REMOTE_HOST:-root@47.77.204.233}"
REMOTE_ROOT="${REMOTE_ROOT:-/root/ours-rp-arm64-compose}"
IMAGE_TAG="${IMAGE_TAG:-ours-rp-runtime-arm64:dev}"
IMAGE_TAR="${IMAGE_TAR:-$REPO_ROOT/target/arm64-docker/ours-rp-runtime-arm64-dev.tar.gz}"
EXECUTE="${EXECUTE:-0}"
INSTALL_DOCKER="${INSTALL_DOCKER:-1}"
INSTALL_BINFMT="${INSTALL_BINFMT:-1}"
START_CORE="${START_CORE:-0}"
START_SIDECARS="${START_SIDECARS:-0}"

usage() {
  cat <<'USAGE'
Usage:
  scripts/docker/deploy_remote233_arm64_compose.sh [options]

Default is dry-run. Pass --execute to modify the remote host.

Options:
  --execute                 Actually install/copy/load/start on remote
  --remote <ssh-host>       SSH host (default: root@47.77.204.233)
  --remote-root <path>      Remote compose root
  --image <tag>             Image tag loaded by docker load
  --image-tar <path>        Local docker save tar.gz
  --no-install-docker       Skip Docker installation
  --no-binfmt               Skip binfmt/qemu installation
  --start-core              Start ours-rp-soak after deploy
  --start-sidecars          Start artifact metrics, Prometheus and Grafana after deploy
  -h, --help                Show this help
USAGE
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --execute)
      EXECUTE=1
      shift
      ;;
    --remote)
      REMOTE_HOST="$2"
      shift 2
      ;;
    --remote-root)
      REMOTE_ROOT="$2"
      shift 2
      ;;
    --image)
      IMAGE_TAG="$2"
      shift 2
      ;;
    --image-tar)
      IMAGE_TAR="$2"
      shift 2
      ;;
    --no-install-docker)
      INSTALL_DOCKER=0
      shift
      ;;
    --no-binfmt)
      INSTALL_BINFMT=0
      shift
      ;;
    --start-core)
      START_CORE=1
      shift
      ;;
    --start-sidecars)
      START_SIDECARS=1
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "unknown option: $1" >&2
      usage >&2
      exit 2
      ;;
  esac
done

require_command() {
  command -v "$1" >/dev/null 2>&1 || {
    echo "missing required command: $1" >&2
    exit 2
  }
}

run_or_echo() {
  if [[ "$EXECUTE" == "1" ]]; then
    "$@"
  else
    printf 'DRY-RUN:'
    printf ' %q' "$@"
    printf '\n'
  fi
}

remote_run() {
  if [[ "$EXECUTE" == "1" ]]; then
    ssh "$REMOTE_HOST" "$@"
  else
    printf 'DRY-RUN: ssh %q %q\n' "$REMOTE_HOST" "$*"
  fi
}

require_command ssh
require_command rsync

[[ -f "$IMAGE_TAR" ]] || {
  echo "missing image tar: $IMAGE_TAR" >&2
  exit 2
}

compose_src="$REPO_ROOT/deploy/arm64-compose/"
[[ -f "$compose_src/docker-compose.yml" ]] || {
  echo "missing compose source: $compose_src" >&2
  exit 2
}

echo "remote=$REMOTE_HOST"
echo "remote_root=$REMOTE_ROOT"
echo "image=$IMAGE_TAG"
echo "image_tar=$IMAGE_TAR"

if [[ "$INSTALL_DOCKER" == "1" ]]; then
  remote_run "if ! command -v docker >/dev/null 2>&1; then apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y docker.io; fi; if ! docker compose version >/dev/null 2>&1; then if apt-cache show docker-compose-plugin >/dev/null 2>&1; then DEBIAN_FRONTEND=noninteractive apt-get install -y docker-compose-plugin; elif apt-cache show docker-compose-v2 >/dev/null 2>&1; then DEBIAN_FRONTEND=noninteractive apt-get install -y docker-compose-v2; elif apt-cache show docker-compose >/dev/null 2>&1; then DEBIAN_FRONTEND=noninteractive apt-get install -y docker-compose; else echo 'no docker compose package found' >&2; exit 2; fi; fi; systemctl enable --now docker || true"
fi

remote_run "mkdir -p '$REMOTE_ROOT/images'"
run_or_echo rsync -a --delete "$compose_src" "$REMOTE_HOST:$REMOTE_ROOT/"
run_or_echo rsync -a "$IMAGE_TAR" "$REMOTE_HOST:$REMOTE_ROOT/images/"

remote_tar="$REMOTE_ROOT/images/$(basename "$IMAGE_TAR")"
remote_run "cd '$REMOTE_ROOT' && test -f .env || cp .env.example .env"
remote_run "gunzip -c '$remote_tar' | docker load"

if [[ "$INSTALL_BINFMT" == "1" ]]; then
  remote_run "docker run --rm --privileged tonistiigi/binfmt --install arm64"
fi

remote_run "docker run --rm --platform linux/arm64 '$IMAGE_TAG' uname -m"
remote_run "docker run --rm --platform linux/arm64 '$IMAGE_TAG' /opt/ours-rp/bin/rpki --help >/tmp/ours-rp-arm64-help.txt && head -5 /tmp/ours-rp-arm64-help.txt"

if [[ "$START_CORE" == "1" ]]; then
  remote_run "cd '$REMOTE_ROOT' && docker compose --profile core up -d ours-rp-soak"
fi

if [[ "$START_SIDECARS" == "1" ]]; then
  remote_run "cd '$REMOTE_ROOT' && docker compose --profile sidecar --profile monitor up -d artifact-metrics prometheus grafana"
fi

remote_run "cd '$REMOTE_ROOT' && docker compose ps"
