#!/usr/bin/env bash
# One-time server setup for mediator on Ubuntu. Run as root ON THE SERVER,
# from a directory containing mediator.service and mediator.nginx.conf:
#
#   sudo ./setup-server.sh <deploy-user> <domain>
#
# <deploy-user>  the account you ssh in as; it gets write access to
#                /opt/mediator and passwordless `systemctl restart mediator`
# <domain>       the public hostname nginx should answer on
set -euo pipefail

DEPLOY_USER="${1:?usage: setup-server.sh <deploy-user> <domain>}"
DOMAIN="${2:?usage: setup-server.sh <deploy-user> <domain>}"
APP_DIR=/opt/mediator
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

id -u "$DEPLOY_USER" >/dev/null

# Unprivileged system user the service runs as.
id -u mediator >/dev/null 2>&1 ||
    useradd --system --home "$APP_DIR" --shell /usr/sbin/nologin mediator

# Deploy user owns the app dir (to replace the binary); the service user
# owns only the data dir (the single thing it writes).
mkdir -p "$APP_DIR/data"
chown "$DEPLOY_USER" "$APP_DIR"
chmod 755 "$APP_DIR"
chown mediator:mediator "$APP_DIR/data"
chmod 750 "$APP_DIR/data"

install -m 644 "$SCRIPT_DIR/mediator.service" /etc/systemd/system/mediator.service

sed "s/mediator\.example\.com/$DOMAIN/" "$SCRIPT_DIR/mediator.nginx.conf" \
    > /etc/nginx/sites-available/mediator
ln -sf /etc/nginx/sites-available/mediator /etc/nginx/sites-enabled/mediator

# Let the deploy user restart the service without a sudo password,
# so deploy.sh needs exactly one (ssh) password prompt.
printf '%s ALL=(root) NOPASSWD: /usr/bin/systemctl restart mediator\n' "$DEPLOY_USER" \
    > /etc/sudoers.d/mediator-deploy
chmod 440 /etc/sudoers.d/mediator-deploy

systemctl daemon-reload
systemctl enable mediator
nginx -t
systemctl reload nginx

echo "Setup done. Now push a binary from your machine: ./deploy/deploy.sh"
echo "For HTTPS: certbot --nginx -d $DOMAIN"
