#!/bin/bash
# First-boot setup
#
# Asks for the root password and the hostname (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. Root adds the ssh keys afterwards
# (README.md).
#
# With the credential agent.password, it asks nothing and takes the answers
# from the credentials agent.password and agent.hostname. mkosi vm passes them
# (mkosi.conf).
set -euo pipefail

# cred prints the credential agent.<name>, and fails if it isn't passed.
cred() { cat "${CREDENTIALS_DIRECTORY:-/nonexistent}/agent.$1" 2>/dev/null; }

if pw=$(cred password); then
  # flock lets only one of the two consoles do the setup.
  exec 9>/run/agent-setup.lock
  flock -n 9 || exit 0
  name=$(cred hostname) || 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
fi

install -d -m 0700 /var/lib/agent/etc
# etc-shadow.mount is stopped first: an interrupted setup may have started it,
# and then cp would copy the shadow file onto itself.
systemctl stop etc-shadow.mount
cp /etc/passwd /etc/shadow /var/lib/agent/etc/
echo "root:$pw" | chpasswd --prefix /var/lib/agent
systemctl start etc-shadow.mount
# hostname is written last: its presence marks the setup as done.
echo "${name:-agent}" > /var/lib/agent/hostname
systemctl start agent-boot.service sshd.service
cat <<'EOF'
Done. Log in as root and add your ssh key for the user claude to
/var/lib/agent/authorized_keys (for root: root_authorized_keys there). Then
log in with ssh claude@<this VM>, run claude and log in with your account.
Remote Control then starts by itself.
EOF
# systemctl stop ends the setup on the other console, which then shows its
# login.
systemctl --no-block stop "agent-setup@*.service"
