#!/usr/bin/env bash
set -euo pipefail

APP_DIR=/opt/basecamp-mcp
BIN_SOURCE=${1:-./basecamp-mcp-linux-amd64}

if [[ $EUID -ne 0 ]]; then echo "Run as root" >&2; exit 1; fi
if [[ ! -f "$BIN_SOURCE" ]]; then echo "Binary not found: $BIN_SOURCE" >&2; exit 1; fi

id basecamp-mcp >/dev/null 2>&1 || useradd --system --home-dir "$APP_DIR" --shell /sbin/nologin basecamp-mcp
mkdir -p "$APP_DIR/data"
install -m 0755 "$BIN_SOURCE" "$APP_DIR/basecamp-mcp"
[[ -f "$APP_DIR/.env" ]] || install -m 0600 .env.example "$APP_DIR/.env"
chown -R basecamp-mcp:basecamp-mcp "$APP_DIR"
install -m 0644 basecamp-mcp.service /etc/systemd/system/basecamp-mcp.service
systemctl daemon-reload
systemctl enable basecamp-mcp

echo "Edit $APP_DIR/.env, then run: systemctl start basecamp-mcp"
