#!/bin/bash
# First-boot setup
#
# Asks for the root password, the hostname and the ssh key of the user claude
# (agent-setup@.service). /etc is read-only, so the answers go to
# /var/lib/agent. The password goes into a shadow file there, which
# etc-shadow.mount puts over /etc/shadow. agent-boot applies the rest 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"
