#!/bin/bash
# First boot: asks for the root password, the hostname and the ssh key of the user claude, on the
# screen (tty1) and the serial console (ttyS0) at once (agent-setup@.service).
# /etc is read-only, so the answers go to /var/lib/agent: the password to a shadow file there
# (etc-shadow.mount puts it over /etc/shadow), the rest is applied by agent-boot at every boot.
set -euo pipefail
echo "== Agent setup =="

while :; do
  read -rsp "Root password: " pw; echo
  read -rsp "Again: " pw2; echo
  [[ -n $pw && $pw == "$pw2" ]] && break
  echo "Passwords do not match, try again."
done
install -d -m 0700 /var/lib/agent/etc
cp /etc/passwd /etc/shadow /var/lib/agent/etc/
echo "root:$pw" | chpasswd --prefix /var/lib/agent
systemctl start etc-shadow.mount

read -rp "Hostname [agent]: " name
read -rp "SSH public key for the user claude: " key
[[ -n $key ]] && install -m 0644 /dev/stdin /var/lib/agent/authorized_keys <<<"$key"
# Written last: its presence marks the setup as done.
echo "${name:-agent}" > /var/lib/agent/hostname
systemctl start agent-boot.service sshd.service
echo "Done. Log in with ssh claude@<this VM>, run claude and log in with your account."
echo "Remote Control then starts by itself."
# Stop the setup on the other console, which then shows its login.
systemctl --no-block stop "agent-setup@*.service"
