#!/usr/bin/sh
#
# Suricatavel Agent CLI Wrapper
#
# Usage: suricatavel-agent [group] [action] [target] [options]
#
# Examples:
#   suricatavel-agent                        # Interactive mode
#   suricatavel-agent status                 # Show system status
#   suricatavel-agent version                # Show installed version
#   suricatavel-agent start                  # Start daemon
#   suricatavel-agent stop                   # Stop daemon
#   suricatavel-agent restart                # Restart daemon
#   suricatavel-agent positions status       # Check log reading offsets
#   suricatavel-agent register --join=svj1.… # Enrol with a join string from the controller (mTLS)
#
# The CLI never runs PHP as root. Run by root, it runs PHP as the service user and
# keeps suricatavel-agent-helper answering its requests for the service and package
# operations that need root, only while the CLI runs.

set -eu

SERVICE_USER=suricatavel

script=$(readlink -f "$0" 2>/dev/null || echo "$0")
script_dir=$(cd "$(dirname "$script")" && pwd -P)

# Application root: an install location, or relative to this script in a checkout.
for candidate in /var/opt/suricatavel-agent/current /var/opt/suricatavel-agent /usr/local/suricatavel-agent \
    "$script_dir/../.." "$script_dir/.."; do
    if [ -f "$candidate/artisan" ]; then
        APP_DIR=$(cd "$candidate" && pwd -P)
        break
    fi
done

if [ -z "${APP_DIR:-}" ]; then
    echo 'Error: Could not find Suricatavel Agent application root' >&2
    exit 1
fi

SURICATAVEL_AGENT_CWD=$(pwd)
export SURICATAVEL_AGENT_CWD

cd "$APP_DIR"

if [ "${1:-}" = --version ] || [ "${1:-}" = -V ]; then
    shift
    set -- version "$@"
fi

if [ "$(id -u)" -ne 0 ]; then
    exec php artisan suricatavel-agent "$@"
fi

if ! id "$SERVICE_USER" >/dev/null 2>&1; then
    echo "Error: the service user '$SERVICE_USER' does not exist." >&2
    exit 1
fi

# Runs a command as the service user, keeping open file descriptors.
as_service_user() {
    if command -v setpriv >/dev/null 2>&1; then
        HOME=$APP_DIR USER=$SERVICE_USER LOGNAME=$SERVICE_USER \
            setpriv --reuid="$SERVICE_USER" --regid="$SERVICE_USER" --init-groups --inh-caps=-all -- "$@"
    elif command -v runuser >/dev/null 2>&1; then
        HOME=$APP_DIR runuser -u "$SERVICE_USER" -- "$@"
    else
        # FreeBSD: chroot(8) to / changes user and groups without a shell of the user.
        HOME=$APP_DIR USER=$SERVICE_USER LOGNAME=$SERVICE_USER \
            chroot -u "$SERVICE_USER" -g "$SERVICE_USER" -G "$(id -Gn "$SERVICE_USER" | tr ' ' ',')" / \
            sh -c 'cd "$1" && shift && exec "$@"' sh "$APP_DIR" "$@"
    fi
}

# Requests reach the helper through two pipes that only this process and its
# children hold: they are opened and unlinked before PHP starts.
channel=$(mktemp -d "${TMPDIR:-/tmp}/suricatavel-agent.XXXXXX")
mkfifo -m 600 "$channel/requests" "$channel/replies"
exec 3<>"$channel/requests" 4<>"$channel/replies"
rm -rf "$channel"

"$APP_DIR/support/bin/suricatavel-agent-helper" --serve <&3 >&4 3>&- 4>&- &
helper=$!
trap 'kill "$helper" 2>/dev/null || true' EXIT
# Ctrl+C reaches PHP, which handles it; the wrapper only waits for it to finish.
trap ':' INT

SURICATAVEL_AGENT_PRIVILEGED_CHANNEL=3,4
export SURICATAVEL_AGENT_PRIVILEGED_CHANNEL

status=0
as_service_user php artisan suricatavel-agent "$@" || status=$?
exit "$status"
