#!/bin/bash
# Set up SSH key infrastructure for git push access.
# Run once on the production server after initial deploy.
#
# Prerequisites: git system user exists (from setup-git-ssh.sh)

set -e

echo "[setup] Configuring SSH key infrastructure..."

# Ensure git user's .ssh directory exists with correct permissions
mkdir -p /opt/git/.ssh
chown git:git /opt/git/.ssh
chmod 700 /opt/git/.ssh

# Create empty authorized_keys if it doesn't exist
touch /opt/git/.ssh/authorized_keys
chown git:git /opt/git/.ssh/authorized_keys
chmod 600 /opt/git/.ssh/authorized_keys

# Ensure mnw-admin binary exists at the expected path
if [ ! -f /opt/makenotwork/mnw-admin ]; then
    echo "[setup] WARNING: /opt/makenotwork/mnw-admin not found."
    echo "        Deploy the binary first, then re-run this script."
fi

# Add sudoers rule: allow makenotwork user to run rebuild-keys as git
SUDOERS_FILE="/etc/sudoers.d/mnw-git-ssh"
if [ ! -f "$SUDOERS_FILE" ]; then
    echo "makenotwork ALL=(git) NOPASSWD: /opt/makenotwork/mnw-admin rebuild-keys" > "$SUDOERS_FILE"
    chmod 440 "$SUDOERS_FILE"
    echo "[setup] Added sudoers rule: $SUDOERS_FILE"
else
    echo "[setup] Sudoers rule already exists: $SUDOERS_FILE"
fi

# Verify sudoers syntax
visudo -cf "$SUDOERS_FILE"

echo "[setup] SSH key infrastructure configured."
echo ""
echo "Next steps:"
echo "  1. Users add SSH keys via the dashboard"
echo "  2. The web app triggers: sudo -u git /opt/makenotwork/mnw-admin rebuild-keys"
echo "  3. SSH clone: git clone git@makenot.work:{username}/{repo}.git"
