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

site_host="${1:?usage: deploy_vps2.sh SITES_ORIGIN_HOST [SSH_TARGET]}"
target="${2:-vps2}"
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
project="$(cd "$script_dir/.." && pwd)"

case "$site_host" in
  *[!A-Za-z0-9.-]*) echo "invalid Sites host" >&2; exit 2 ;;
esac
curl --silent --show-error --fail "https://$site_host/" >/dev/null

mapfile -t wheels < <(find "$project/dist-py" -maxdepth 1 -type f -name 'backplane_runtime-*.whl' -print)
if test "${#wheels[@]}" -ne 1; then
  echo "expected exactly one Backplane wheel in $project/dist-py" >&2
  exit 2
fi

wheel="${wheels[0]}"
wheel_name="$(basename "$wheel")"
release_id="$(date -u +%Y%m%dT%H%M%SZ)-$(git -C "$project" rev-parse --short=10 HEAD)"
remote_payload="/tmp/backplane-deploy-$release_id"

ssh "$target" "mkdir -p '$remote_payload'"
scp \
  "$wheel" \
  "$script_dir/backplane-runtime.service" \
  "$script_dir/nginx.bootstrap.conf" \
  "$script_dir/nginx.backplane.conf.template" \
  "$script_dir/install_remote.sh" \
  "$target:$remote_payload/"

ssh "$target" \
  "sudo bash '$remote_payload/install_remote.sh' '$release_id' '$site_host' '$wheel_name' '$remote_payload'"
ssh "$target" "rm -rf '$remote_payload'"

printf '%s\n' "https://backplane.cyberelf.link/"
