#!/bin/sh
# agent-bootstrap.sh
#
# Run INSIDE a guest (via SSH, console, or guest-agent) to bring the
# system fully under agent management in one shot:
#   1. install + enable qemu-guest-agent  (VMs only, skipped on bare metal)
#   2. push the agent SSH key to root + AGENT_USER (+ labuser if present)
#   3. grant AGENT_USER passwordless sudo
#
# AGENT_USER defaults to "localuser". Override for systems with a different
# unprivileged agent user:
#   AGENT_USER=subodev bash agent-bootstrap.sh
#
# After this runs once, the agent has SSH+sudo immediately.
#
# Usage (from a root shell in the guest):
#   bash agent-bootstrap.sh
#   AGENT_USER=subodev bash agent-bootstrap.sh

set -eu

KEY='ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIWms/uCXnjjo4KyxHBcYI2TDHe8OZ2wle6W/0hSRQLu reachableceo@ultix-streaming'
AGENT_USER="${AGENT_USER:-localuser}"

# 1. guest-agent (skip on bare metal — no virtio-serial device)
if command -v systemd-detect-virt >/dev/null 2>&1 && \
   [ "$(systemd-detect-virt --vm 2>/dev/null || echo none)" != "none" ]; then
  if ! command -v qemu-ga >/dev/null 2>&1; then
    if command -v apt-get >/dev/null 2>&1; then
      apt-get update
      DEBIAN_FRONTEND=noninteractive apt-get install -y qemu-guest-agent
    elif command -v dnf >/dev/null 2>&1; then
      dnf install -y qemu-guest-agent
    elif command -v yum >/dev/null 2>&1; then
      yum install -y qemu-guest-agent
    else
      echo "WARN: no supported package manager; skipping agent install" >&2
    fi
  fi
  systemctl enable --now qemu-guest-agent 2>/dev/null || \
    systemctl enable --now qemu-ga 2>/dev/null || true
fi

# 2. SSH key for root + AGENT_USER + labuser (if present)
for u in root "$AGENT_USER" labuser; do
  if ! getent passwd "$u" >/dev/null 2>&1; then continue; fi
  H=$(getent passwd "$u" | cut -d: -f6)
  mkdir -p "$H/.ssh"; chmod 700 "$H/.ssh"
  AK="$H/.ssh/authorized_keys"; touch "$AK"; chmod 600 "$AK"
  grep -qF "$KEY" "$AK" || echo "$KEY" >> "$AK"
  chown -R "$u": "$H/.ssh"
done

# 3. passwordless sudo for AGENT_USER only
if getent passwd "$AGENT_USER" >/dev/null 2>&1 && [ -d /etc/sudoers.d ]; then
  echo "${AGENT_USER} ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/010-agent
  chmod 440 /etc/sudoers.d/010-agent
fi

echo BOOTSTRAP-DONE
