#!/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.
#
# With the credential agent.password, it asks nothing and takes the answers
# from the credentials agent.password, agent.hostname and agent.ssh-key, such
# as for a test VM (README.md).
set -euo pipefail
cred() { cat "${CREDENTIALS_DIRECTORY:-/nonexistent}/agent.$1" 2>/dev/null; }

if pw=$(cred password); then
  # Both consoles run this script. Only one may do the setup.
  exec 9>/run/agent-setup.lock
  flock -n 9 || exit 0
  name=$(cred hostname) || true
  key=$(cred ssh-key) || true
else
  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
  read -rp "Hostname [agent]: " name
  read -rp "SSH public key for the user claude: " key
fi

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
[[ -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"
