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

usage() {
  cat <<'EOF'
Usage: prepare_titan_rpi4_replacement.sh <node> [remote-host]

Build a node-specific recovery image for a Titan rpi4 Longhorn worker and
optionally copy it to a remote flashing station such as `tethys`.

Examples:
  ./scripts/prepare_titan_rpi4_replacement.sh titan-13
  ./scripts/prepare_titan_rpi4_replacement.sh titan-19 tethys
EOF
}

if [ "${1:-}" = "" ] || [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then
  usage
  exit 0
fi

node="$1"
remote_host="${2:-}"
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cache_dir="${METIS_CACHE_DIR:-${HOME}/.cache/metis}"
remote_dir="${METIS_REMOTE_DIR:-/tmp/metis-images}"

case "${node}" in
  titan-13|titan-19)
    ;;
  *)
    echo "Refusing unknown replacement target: ${node}" >&2
    exit 1
    ;;
esac

cd "${repo_root}"

if [ -z "${METIS_IMAGE_RPI4_ARMBIAN_LONGHORN:-}" ]; then
  export METIS_IMAGE_RPI4_ARMBIAN_LONGHORN="file://${HOME}/Downloads/Armbian_25.8.1_Rpi4b_noble_current_6.12.41.img"
fi

if [ -z "${METIS_K3S_TOKEN:-}" ]; then
  export METIS_K3S_TOKEN="$(ssh titan-0a 'sudo cat /var/lib/rancher/k3s/server/node-token')"
fi

echo "Deleting stale Kubernetes node object for ${node}..."
kubectl delete node "${node}" --ignore-not-found

echo "Building recovery image for ${node}..."
go run ./cmd/metis image \
  --inventory inventory.titan-rpi4.yaml \
  --node "${node}" \
  --cache "${cache_dir}" \
  --output "artifacts/${node}.img"

sha256sum "artifacts/${node}.img"

if [ -n "${remote_host}" ]; then
  echo "Copying artifacts/${node}.img to ${remote_host}:${remote_dir}/ ..."
  ssh "${remote_host}" "mkdir -p '${remote_dir}'"
  scp "artifacts/${node}.img" "${remote_host}:${remote_dir}/${node}.img"
fi

cat <<EOF

Prepared artifacts/${node}.img

Next steps:
  1. Ask for the SD card to be inserted into the flashing station.
  2. Run ./scripts/remote_sd_candidates.sh ${remote_host:-tethys}
  3. Run ./scripts/remote_flash_titan_image.sh ${remote_host:-tethys} ${node} /dev/sdX
EOF
