#!/usr/bin/sh
#
# Suricatavel CLI Wrapper
#
# Usage: suricatavel [group] [action] [target] [options]
#
# Examples:
#   suricatavel                        # Interactive mode
#   suricatavel status                 # Show system status
#   suricatavel version                # Show installed version
#   suricatavel workers status         # Show workers status
#   suricatavel stop kafka             # Stop kafka consumer
#   suricatavel restart events         # Restart events worker
#   suricatavel update                 # Update Suricatavel
#   suricatavel deploy --migrate       # Run deployment tasks
#
# The CLI never runs PHP as root. Run by root, it runs PHP as the service user and
# keeps suricatavel-helper answering its requests for the supervisor 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 /usr/share/suricatavel "$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 application root' >&2
    exit 1
fi

SURICATAVEL_CWD=$(pwd)
export SURICATAVEL_CWD

cd "$APP_DIR"

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

if [ "$(id -u)" -ne 0 ]; then
    exec php artisan suricatavel "$@"
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() {
    service_home=$(getent passwd "$SERVICE_USER" | cut -d: -f6)
    if command -v setpriv >/dev/null 2>&1; then
        HOME=${service_home:-$APP_DIR} USER=$SERVICE_USER LOGNAME=$SERVICE_USER \
            setpriv --reuid="$SERVICE_USER" --regid="$SERVICE_USER" --init-groups --inh-caps=-all -- "$@"
    else
        HOME=${service_home:-$APP_DIR} runuser -u "$SERVICE_USER" -- "$@"
    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.XXXXXX")
mkfifo -m 600 "$channel/requests" "$channel/replies"
exec 3<>"$channel/requests" 4<>"$channel/replies"
rm -rf "$channel"

"$APP_DIR/support/bin/suricatavel-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_PRIVILEGED_CHANNEL=3,4
export SURICATAVEL_PRIVILEGED_CHANNEL

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