#!/bin/bash
# One-time server setup: create app user, /opt/beanflows, and GitLab deploy key.
# Run as root on a fresh Hetzner server before bootstrapping the supervisor.
#
# Usage:
#   bash infra/setup_server.sh

set -euo pipefail

APP_USER="beanflows_service"
APP_DIR="/opt/beanflows"
KEY_PATH="/home/$APP_USER/.ssh/gitlab_deploy"

# Create system user with a home dir (needed for .ssh) but no login shell
if ! id "$APP_USER" &>/dev/null; then
    useradd --system --create-home --shell /usr/sbin/nologin "$APP_USER"
    echo "Created user: $APP_USER"
else
    echo "User $APP_USER already exists, skipping"
fi

# Create app directory owned by app user
mkdir -p "$APP_DIR"
chown "$APP_USER:$APP_USER" "$APP_DIR"
chmod 750 "$APP_DIR"
echo "Created $APP_DIR (owner: $APP_USER)"

# Generate deploy key if not already present
if [ ! -f "$KEY_PATH" ]; then
    mkdir -p "/home/$APP_USER/.ssh"
    ssh-keygen -t ed25519 -f "$KEY_PATH" -N "" -C "beanflows-server"
    chown -R "$APP_USER:$APP_USER" "/home/$APP_USER/.ssh"
    chmod 700 "/home/$APP_USER/.ssh"
    chmod 600 "$KEY_PATH"
    chmod 644 "$KEY_PATH.pub"
    echo "Generated deploy key: $KEY_PATH"
else
    echo "Deploy key already exists, skipping"
fi

echo ""
echo "=== Add this deploy key to GitLab ==="
echo "GitLab → repo → Settings → Repository → Deploy Keys (read-only)"
echo ""
cat "$KEY_PATH.pub"
