#!/bin/bash
# Setup SSH git access on the production VPS.
#
# Creates a `git` system user with /bin/sh shell, home directory at /opt/git/.
# SSH access is controlled by authorized_keys command= restrictions (managed
# by mnw-admin rebuild-keys), not by the login shell.
#
# Run as root on the production VPS.

set -euo pipefail

GIT_HOME="/opt/git"

# 1. Create git system user (shell=/bin/sh — security via authorized_keys command=)
if id git &>/dev/null; then
    echo "git user already exists"
else
    useradd --system --shell /bin/sh --home-dir "$GIT_HOME" --no-create-home git
    echo "Created git user"
fi

# Ensure home dir and shell are set correctly
usermod --home "$GIT_HOME" --shell /bin/sh git

# 2. Set up SSH directory (authorized_keys managed by mnw-admin rebuild-keys)
mkdir -p "$GIT_HOME/.ssh"
touch "$GIT_HOME/.ssh/authorized_keys"
chmod 700 "$GIT_HOME/.ssh"
chmod 600 "$GIT_HOME/.ssh/authorized_keys"

# 3. Ensure /opt/git/ repos are owned by git user
chown -R git:git "$GIT_HOME"

# The makenotwork service needs read access to /opt/git/ for the web browser.
# The service runs as makenotwork user. Add makenotwork to git group for read access.
usermod -aG git makenotwork 2>/dev/null || true

# Ensure group read on repo dirs
chmod -R g+rX "$GIT_HOME"

echo ""
echo "=== Git SSH setup complete ==="
echo ""
echo "Next: run setup-ssh-keys.sh to configure sudoers for authorized_keys management"
