#!/bin/sh
# perlistream-server [--check | --print-setup-url | --version | ...]
# perlistream-server setup-url            the URLs of the setup page (real port)
# perlistream-server grant FOLDER [--write]   let the service read (or write) a folder
# perlistream-server run-as USER|--default    run the service as another user
#
# Thin wrapper around server_main.py with the bundled venv. When run as root it
# drops to the service user, so a `sudo perlistream-server --check` cannot
# leave root-owned files in the data directory.
#
# The service's environment is read the way systemd builds it: the unit's
# Environment= lines INCLUDING drop-ins (`systemctl edit`), then
# /etc/default/perlistream-server, which wins. So a port changed in either
# place is the port every command here reports.
set -eu

SELF="$(readlink -f "$0" 2>/dev/null || echo "$0")"
PREFIX="$(cd "$(dirname "$SELF")/.." && pwd)"
PY="$PREFIX/venv/bin/python"
MAIN="$PREFIX/app/server_main.py"
UNIT=perlistream-server.service

case "${1:-}" in
    grant|run-as)
        exec "$PREFIX/bin/perlistream-grant" "$@"
        ;;
esac

# PERLISTREAM_* from the unit (+ drop-ins). Values are root-owned config.
if [ -d /run/systemd/system ] && command -v systemctl >/dev/null 2>&1; then
    _unit_env="$(systemctl show -p Environment --value "$UNIT" 2>/dev/null || true)"
    if [ -n "$_unit_env" ]; then
        _tmp="$(printf '%s\n' "$_unit_env" | xargs -n1 printf '%s\n' 2>/dev/null || true)"
        _old_ifs="$IFS"
        IFS='
'
        for _kv in $_tmp; do
            case "$_kv" in
                PERLISTREAM_[A-Z_]*=*) export "$_kv" ;;
            esac
        done
        IFS="$_old_ifs"
    fi
fi
if [ -f /etc/default/perlistream-server ]; then
    set -a
    # shellcheck disable=SC1091
    . /etc/default/perlistream-server
    set +a
fi
export PERLISTREAM_EDITION="${PERLISTREAM_EDITION:-server}"
export PERLISTREAM_DATA_DIR="${PERLISTREAM_DATA_DIR:-/var/lib/perlistream}"
export PERLISTREAM_PACKAGING="${PERLISTREAM_PACKAGING:-deb}"

if [ "${1:-}" = "setup-url" ]; then
    shift
    set -- --print-setup-url "$@"
fi

if [ ! -x "$PY" ]; then
    echo "perlistream-server: $PY missing — run: sudo $PREFIX/bin/setup-venv.sh" >&2
    exit 1
fi
cd "$PREFIX/app"

# The user the service runs as (run-as may have changed it).
SVC_USER=perlistream
if [ -d /run/systemd/system ] && command -v systemctl >/dev/null 2>&1; then
    _u="$(systemctl show -p User --value "$UNIT" 2>/dev/null || true)"
    [ -n "$_u" ] && SVC_USER="$_u"
fi

if [ "$(id -u)" -eq 0 ] && [ "$SVC_USER" != root ] && id "$SVC_USER" >/dev/null 2>&1; then
    if command -v runuser >/dev/null 2>&1; then
        exec runuser -u "$SVC_USER" -- "$PY" "$MAIN" "$@"
    fi
    exec setpriv --reuid="$SVC_USER" --regid="$(id -g "$SVC_USER")" --init-groups "$PY" "$MAIN" "$@"
fi
exec "$PY" "$MAIN" "$@"
