#!/bin/bash
# Runs LOCALLY. Boots the machine into the dropbear rescue environment.
#
# What happens:
#   grub-reboot sets a one-time boot to 'dropbear-rescue'. CC VMs
#   cannot reboot from inside the guest, and an in-guest shutdown often
#   leaves the VM in the "running" state in Verda — so the user must run
#   shutdown and then start from the Verda console. On next boot the
#   machine loads the standard Ubuntu kernel with the Ubuntu initramfs
#   (which includes dropbear). The initramfs:
#     1. Loads all virtio drivers via udev (same path as normal boot)
#     2. Configures eth0 via DHCP (dropbear-initramfs hook)
#     3. Starts dropbear sshd on port 22
#     4. Hits 'break=mount' and drops to an interactive shell on tty1
#        (visible on VNC — this is expected and harmless)
#   /dev/vda is NOT mounted at this point and is free to flash.
#
# All ssh calls below use StrictHostKeyChecking=no since the rescue
# environment's dropbear has its own host keys, distinct from the OS's.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
source "$SCRIPT_DIR/.env"

: "${REMOTE:?Edit .env and set REMOTE}"

ENTRY_ID="dropbear-rescue"

echo "==> Setting next GRUB boot to '$ENTRY_ID' on $REMOTE"
ssh $SSH_OPTS "$REMOTE" "grub-reboot '$ENTRY_ID' && sync && sync"
ssh $SSH_OPTS "$REMOTE" "grub-editenv /boot/grub/grubenv list"

echo ""
echo "==> grub-reboot armed. The VM must now be cycled via the Verda console."
ssh $SSH_OPTS \
  "$REMOTE" "poweroff &>/dev/null &" 2>/dev/null || true
echo ""
echo "CC VMs cannot reboot from inside the guest, and an in-guest"
echo "shutdown often leaves the VM marked 'running' in Verda."
echo ">>> In the Verda console: Shutdown the VM, then Start it again. <<<"
echo "    (Both actions are required — Start alone will not pick up the"
echo "     one-shot grub-reboot if the VM never actually stopped.)"
echo ""
echo "Waiting for SSH (dropbear on port 22) once the VM is back up..."

for i in $(seq 1 120); do
  sleep 5
  if ssh -o ConnectTimeout=4 -o BatchMode=yes \
        $SSH_OPTS "$REMOTE" true 2>/dev/null; then
    echo ""
    echo "==> $REMOTE is up in rescue mode."
    echo ""
    echo "Next step:"
    echo "  ./03_upload_and_flash.sh"
    exit 0
  fi
  echo "  ... still waiting ($((i * 5))s) — did you Shutdown then Start the VM in the Verda console?"
done

echo ""
echo "WARNING: SSH did not come up within 600 s."
echo "Check that the VM was Shutdown AND then Started from the Verda console."
echo "If the prompt is there, try connecting manually: ssh $REMOTE"
