#!/usr/bin/env bash
# Blank-server bootstrap. Served by the in-cluster dist nginx; run with:
#   curl -fsSL https://<dist-domain>/bootstrap.sh | PUBLIC_HOST=<numeric-ip> bash
# build-bundle.sh bakes the bundle URL into https://relay-dist.dev.4qube.ru/relay-deploy.zip.
#
# Unpacks into a PERSISTENT install dir (default ~/meshchat-relay, override with
# INSTALL_DIR=...). Safe to re-run to UPDATE: bundle files (compose, install.sh,
# image.tar, k8s) are overwritten, but ./data (bbolt + node keys) and ./.env are
# preserved. Never deploys into a temp dir — the relay's state must outlive this
# script.
set -euo pipefail

BUNDLE_URL="https://relay-dist.dev.4qube.ru/relay-deploy.zip"
[ "$(id -u)" -eq 0 ] && SUDO="" || SUDO="sudo"

# Persistent destination. Resolve a sensible HOME even under `sudo bash`.
DEST="${INSTALL_DIR:-${HOME:-$(getent passwd "$(id -un)" | cut -d: -f6)}/meshchat-relay}"

# Download the zip into a throwaway temp dir (only the archive is ephemeral).
DL="$(mktemp -d)"
trap 'rm -rf "$DL"' EXIT
echo "==> downloading ${BUNDLE_URL}"
curl -fsSL "$BUNDLE_URL" -o "$DL/relay-deploy.zip"

if ! command -v unzip >/dev/null; then
  echo "==> installing unzip"
  $SUDO apt-get update -y && $SUDO apt-get install -y unzip
fi

echo "==> unpacking bundle into ${DEST} (preserving any existing data/ and .env)"
mkdir -p "$DEST"
# -o overwrites bundle files (compose/install.sh/image.tar/k8s) but the archive
# contains no data/ or .env, so existing state is untouched.
unzip -qo "$DL/relay-deploy.zip" -d "$DEST"
cd "$DEST"

# PUBLIC_HOST from env, else prompt on the terminal (stdin is the piped script).
if [ -z "${PUBLIC_HOST:-}" ] && [ -e /dev/tty ]; then
  read -rp "Node's numeric public IP (PUBLIC_HOST): " PUBLIC_HOST </dev/tty
fi
if [ -z "${PUBLIC_HOST:-}" ]; then
  echo "ERROR: PUBLIC_HOST required — re-run with: ... | PUBLIC_HOST=<ip> bash" >&2
  exit 1
fi
export PUBLIC_HOST

chmod +x install.sh
./install.sh

echo "==> deployed in ${DEST} (state in ${DEST}/data — back this directory up)"
