#!/usr/bin/env bash
# Run as sudo on coolify-server-mtl:
#   bash /tmp/setup-vibn-logs-user.sh
#
# Creates a locked-down `vibn-logs` user that the vibn-frontend
# control plane can SSH to. Membership in the `docker` group lets
# it run `docker ps` / `docker logs` without sudo; no shell login,
# no password, single authorized key.

set -euo pipefail

USER=vibn-logs
PUBKEY='ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINkn70ItA4LUZTZDIu8fC8QkuHAewk5VH9ogF+52UTT0 vibn-logs@vibn-frontend'

if id "$USER" &>/dev/null; then
  echo "user $USER already exists"
else
  useradd -m -s /bin/bash "$USER"
  echo "created user $USER"
fi

usermod -aG docker "$USER"
passwd -l "$USER" >/dev/null

mkdir -p "/home/$USER/.ssh"
chmod 700 "/home/$USER/.ssh"

# Exactly one authorized key (force-restrict: no PTY, no agent forwarding,
# no X11 forwarding, no port forwarding). The control plane only needs
# to run docker commands.
AUTH_FILE="/home/$USER/.ssh/authorized_keys"
RESTRICTIONS='no-agent-forwarding,no-port-forwarding,no-X11-forwarding,no-pty'
echo "$RESTRICTIONS $PUBKEY" > "$AUTH_FILE"
chmod 600 "$AUTH_FILE"
chown -R "$USER:$USER" "/home/$USER/.ssh"

echo "✓ $USER ready"
echo "  groups: $(id -nG "$USER")"
echo "  authorized_keys:"
sed 's/^/    /' "$AUTH_FILE"

# Verify docker access
su - "$USER" -s /bin/bash -c 'docker ps --format "table {{.Names}}" | head -3' || {
  echo "⚠ docker access test failed — user may not be able to run docker commands"
  exit 1
}
echo "✓ docker access verified"
