#!/bin/bash
# After the graphical Calamares install finishes and the VM reboots into the
# installed desktop, there's no SSH access yet. This script logs into the
# SDDM/plasmalogin greeter and a terminal via simulated keystrokes (since we
# only have graphical console access at this point), enables sshd, and opens
# the firewall for SSH. After this, 03-setup-ssh-key.sh can take over via
# real SSH.
#
# Assumes: VM is running, at the login screen, with a terminal already
# reachable (e.g. the ML4W desktop auto-opens one, or open one manually via
# virt-viewer first). Adjust/extend the keystrokes below if your desktop
# differs.
set -euo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")"
source ./00-config.sh

type_vm() { VM_NAME="$VM_NAME" ./type_into_vm.sh "$@"; }

echo ">>> Logging in at the greeter (password only; username is pre-filled)"
sudo virsh -c qemu:///system send-key "$VM_NAME" --codeset linux KEY_ENTER
sleep 1
type_vm "$VM_PASSWORD" --enter
sleep 3

echo ">>> Enabling sshd (assumes a terminal is focused on screen)"
type_vm "sudo systemctl enable --now sshd" --enter
sleep 1.5
type_vm "$VM_PASSWORD" --enter
sleep 2

echo ">>> Opening the firewall for SSH"
type_vm "sudo ufw allow ssh" --enter
sleep 2

echo ">>> Checking SSH reachability from the host"
nmap -Pn -p 22 "$VM_IP"
echo ">>> If port 22 shows 'open', continue with 03-setup-ssh-key.sh"
