#!/usr/bin/env bash
#
# Purpose : Create and manage CoreServer VMs (Federated Core's server image)
#           on local KVM, on coreapp-dev's `coreapp` network.
#
# coreapp-vm create [name]       create a VM (downloads the image if missing)
# coreapp-vm list                VMs and their addresses
# coreapp-vm ip [name]           a VM's address
# coreapp-vm ssh [name] [cmd]    log in as root (or run cmd on it)
# coreapp-vm start|stop [name]   start / shut down
# coreapp-vm delete [name]       delete a VM and its disk (asks first)
#
# name defaults to coreserver. Env overrides for create: VCPUS, RAM_MB,
# DISK_GB, NETWORK, MAC.

set -euo pipefail

URI="qemu:///system"
DATA="$HOME/.local/share/coreapp-dev"
IMAGE_NAME="coreserver-enterprise-x86-26-05-12.qcow2"
IMAGE_URL="https://nginx.core-x86builder.federatedcomputer.cloud/$IMAGE_NAME"
# Not published by Federated: the SHA-256 of our first download (2026-12-02)
IMAGE_SHA256="8c3a64e9be12121b71e1a3ad3dd7c6de686734b83ee77f3852d80cee1b6dd4a4"
BASE="$DATA/images/$IMAGE_NAME"
# The image's accounts have locked passwords; root logs in with this key,
# which cloud-init (NoCloud) installs on first boot.
SSH_KEY="$DATA/ssh/id_ed25519"
KNOWN_HOSTS="$DATA/ssh/known_hosts"
EXTRA_KEYS="$HOME/.config/coreapp-dev/authorized_keys"
POOL="default"
POOL_DIR="/var/lib/libvirt/images"

v() { virsh -c "$URI" "$@"; }

usage() {
  sed -n '/^# coreapp-vm /s/^# //p' "${BASH_SOURCE[0]}"
  echo
  echo "To see a VM's screen: virt-viewer -c $URI <name>"
}

exists() { v dominfo "$1" &> /dev/null; }

need_vm() {
  exists "$1" || { echo "No VM named '$1'. coreapp-vm list shows them." >&2; exit 1; }
}

# The VM's IPv4 address, from libvirt's DHCP leases; nothing if it has none
vm_ip() {
  v domifaddr "$1" 2> /dev/null | awk '/ipv4/ {split($4, a, "/"); print a[1]; exit}'
}

download_image() {
  [[ -f "$BASE" ]] && return 0
  echo "Downloading the CoreServer image (1.3 GB) to $BASE..."
  mkdir -p "$(dirname "$BASE")"
  # Resumes a download that was interrupted
  curl -fL --retry 3 --progress-bar -C - -o "$BASE.part" "$IMAGE_URL"
  echo "Checking the download..."
  if [[ "$(sha256sum "$BASE.part" | cut -d' ' -f1)" != "$IMAGE_SHA256" ]]; then
    rm -f "$BASE.part"
    echo "The download isn't the image coreapp-dev was tested with (SHA-256 differs)." >&2
    echo "Deleted it; run create again to retry." >&2
    exit 1
  fi
  mv "$BASE.part" "$BASE"
}

cmd_create() {
  local name="$1"
  local vcpus="${VCPUS:-4}" ram_mb="${RAM_MB:-8192}" disk_gb="${DISK_GB:-60}"
  local network="${NETWORK:-coreapp}" mac="${MAC:-}"
  local vol="$name.qcow2" user_data ip
  # coreapp's DHCP gives this MAC 10.123.0.10, corerelay's default target
  if [[ "$name" == coreserver && -z "$mac" ]]; then mac=52:54:00:c0:4e:10; fi

  if exists "$name"; then
    echo "VM '$name' already exists." >&2; exit 1
  fi
  if v vol-info "$vol" --pool "$POOL" &> /dev/null; then
    echo "Disk '$POOL_DIR/$vol' already exists; coreapp-vm delete $name, or pick another name." >&2
    exit 1
  fi
  if ! v net-info "$network" &> /dev/null; then
    echo "Network '$network' doesn't exist. Run coreapp-dev's update.sh (or CoreDesktop's update)." >&2
    exit 1
  fi
  if [[ ! -f "$EXTRA_KEYS" ]]; then
    echo "Note: $EXTRA_KEYS is missing. Put the SSH key from Federated's dashboard"
    echo "(Cores) there before creating the VM, or the Provisioner can't log in."
  fi

  download_image

  if [[ ! -f "$SSH_KEY" ]]; then
    mkdir -p "$(dirname "$SSH_KEY")"
    ssh-keygen -q -t ed25519 -N "" -C "coreapp-dev" -f "$SSH_KEY"
  fi

  # cloud-init user-data: root may log in, with these keys only
  user_data="$(mktemp)"
  trap 'rm -f "$user_data"' EXIT
  {
    echo "#cloud-config"
    echo "disable_root: false"
    echo "ssh_pwauth: false"
    # Federated Core's DNS server (pdns) needs port 53. Its installer disables
    # systemd-resolved, but this image's systemd-networkd starts it again at
    # boot (systemd-networkd-resolve-hook.socket), so pdns can't start after a
    # reboot. resolv.conf is a plain file (1.1.1.1), so nothing needs resolved.
    echo "bootcmd:"
    echo "  - [systemctl, mask, --now, systemd-resolved.service]"
    echo "ssh_authorized_keys:"
    { cat "$SSH_KEY.pub"; if [[ -f "$EXTRA_KEYS" ]]; then cat "$EXTRA_KEYS"; fi; } \
      | grep -E '^(ssh-|ecdsa-|sk-)' | sed 's/^/  - /'
  } > "$user_data"
  echo "Root's SSH keys: $(grep -c '^  - ' "$user_data") (coreapp-dev's, plus $EXTRA_KEYS)"

  # libvirtd runs as root, so letting it manage the disk avoids sudo here.
  if ! v pool-info "$POOL" &> /dev/null; then
    v pool-define-as "$POOL" dir --target "$POOL_DIR" > /dev/null
    v pool-build "$POOL" > /dev/null 2>&1 || true
  fi
  v pool-start "$POOL" > /dev/null 2>&1 || true
  v pool-autostart "$POOL" > /dev/null
  v pool-refresh "$POOL" > /dev/null

  # Copy the pristine image (keeps the download reusable), then grow it.
  # The image's grow-federated.service gives the extra space to /federated.
  echo "Copying the image to a ${disk_gb} GB disk..."
  v vol-create-as "$POOL" "$vol" "${disk_gb}G" --format qcow2 > /dev/null
  v vol-upload "$vol" "$BASE" --pool "$POOL" --sparse
  v vol-resize "$vol" "${disk_gb}G" --pool "$POOL" > /dev/null

  v net-start "$network" &> /dev/null || true

  # The image needs a display device: it stalls at "Loading initial ramdisk"
  # with --graphics none
  virt-install --connect "$URI" \
    --name "$name" \
    --vcpus "$vcpus" --cpu host-passthrough \
    --memory "$ram_mb" \
    --disk "path=$POOL_DIR/$vol,format=qcow2,bus=virtio" \
    --import \
    --osinfo detect=on,require=off \
    --network "network=$network,model=virtio${mac:+,mac=$mac}" \
    --cloud-init "user-data=$user_data" \
    --graphics vnc,listen=127.0.0.1 --console pty,target_type=serial \
    --noautoconsole > /dev/null

  echo "Created '$name'. Waiting for an IP..."
  for _ in $(seq 1 60); do
    ip="$(vm_ip "$name")"
    if [[ -n "$ip" ]]; then
      echo "IP: $ip"
      echo "Log in: coreapp-vm ssh$([[ "$name" == coreserver ]] || echo " $name")   (cloud-init needs a minute more)"
      exit 0
    fi
    sleep 2
  done
  echo "No IP yet. Watch the screen: virt-viewer -c $URI $name" >&2
  exit 1
}

cmd_list() {
  local name state ip
  printf '%-20s %-10s %s\n' NAME STATE IP
  while read -r name; do
    [[ -n "$name" ]] || continue
    state="$(v domstate "$name" 2> /dev/null)"
    ip=""
    [[ "$state" == running ]] && ip="$(vm_ip "$name")"
    printf '%-20s %-10s %s\n' "$name" "$state" "$ip"
  done < <(v list --all --name)
}

cmd_ip() {
  local ip
  need_vm "$1"
  ip="$(vm_ip "$1")"
  [[ -n "$ip" ]] || { echo "'$1' has no address (is it running?)" >&2; exit 1; }
  echo "$ip"
}

cmd_ssh() {
  local name="$1" ip
  shift
  ip="$(cmd_ip "$name")"
  # Its own known_hosts: a re-created VM gets a new host key at the same IP
  exec ssh -i "$SSH_KEY" -o UserKnownHostsFile="$KNOWN_HOSTS" \
    -o StrictHostKeyChecking=accept-new "root@$ip" "$@"
}

cmd_start() {
  need_vm "$1"
  if [[ "$(v domstate "$1")" == running ]]; then echo "'$1' is already running."; return; fi
  v start "$1" > /dev/null
  echo "Started '$1'."
}

cmd_stop() {
  need_vm "$1"
  if [[ "$(v domstate "$1")" != running ]]; then echo "'$1' isn't running."; return; fi
  v shutdown "$1" > /dev/null
  echo -n "Shutting down '$1'..."
  for _ in $(seq 1 60); do
    if [[ "$(v domstate "$1")" == "shut off" ]]; then echo " done."; return; fi
    sleep 2
  done
  echo
  echo "Still running after 2 minutes. To force it off: virsh -c $URI destroy $1" >&2
  exit 1
}

cmd_delete() {
  local name="$1" ip answer
  need_vm "$name"
  ip="$(vm_ip "$name")"
  echo "This deletes VM '$name' and its disk $POOL_DIR/$name.qcow2, with everything"
  echo "on it. The downloaded image is kept."
  echo
  echo "If a Federated Core was provisioned on it, delete that Core in the dashboard"
  echo "before you put another VM behind the same public IP: deleting a Core makes"
  echo "Federated log in to its IP and tear down whatever it finds there."
  echo
  read -r -p "Type the VM's name to delete it: " answer
  [[ "$answer" == "$name" ]] || { echo "Not deleted."; exit 1; }
  if [[ "$(v domstate "$name")" == running ]]; then v destroy "$name" > /dev/null; fi
  v undefine "$name" --nvram > /dev/null 2>&1 || v undefine "$name" > /dev/null
  v vol-delete "$name.qcow2" --pool "$POOL" > /dev/null 2>&1 || true
  if [[ -n "$ip" && -f "$KNOWN_HOSTS" ]]; then
    ssh-keygen -q -R "$ip" -f "$KNOWN_HOSTS" > /dev/null 2>&1 || true
    rm -f "$KNOWN_HOSTS.old"
  fi
  echo "Deleted '$name'."
}

cmd="${1:-help}"
[[ $# -gt 0 ]] && shift
case "$cmd" in
  create) cmd_create "${1:-coreserver}" ;;
  list | ls) cmd_list ;;
  ip) cmd_ip "${1:-coreserver}" ;;
  ssh)
    # The first argument is a VM's name if there's a VM by that name
    name=coreserver
    if [[ $# -gt 0 ]] && exists "$1"; then name="$1"; shift; fi
    cmd_ssh "$name" "$@"
    ;;
  start) cmd_start "${1:-coreserver}" ;;
  stop) cmd_stop "${1:-coreserver}" ;;
  delete | rm) cmd_delete "${1:-coreserver}" ;;
  help | -h | --help) usage ;;
  *) usage >&2; exit 1 ;;
esac
