#!/bin/sh
#
# Suricatavel Agent privileged helper
#
# The only part of the agent that may run as root. It never runs PHP: it runs a
# fixed set of service and package operations for the service manager the agent
# was installed with, and checks every argument it is given.
#
# Usage:
#   suricatavel-agent-helper manager
#   suricatavel-agent-helper service status|start|stop|restart
#   suricatavel-agent-helper daemon running|start|ready
#   suricatavel-agent-helper package refresh
#   suricatavel-agent-helper package available
#   suricatavel-agent-helper package install [version]
#   suricatavel-agent-helper --serve
#
# With --serve it answers the requests of the CLI wrapper: one request per line on
# standard input ("service restart"), and for each one "<exit code> <bytes>\n"
# followed by that many bytes of output on standard output.
#
# The service manager (systemd, supervisor or rcd) is read from
# /etc/suricatavel-agent/service-manager (/usr/local/etc/... on FreeBSD), written
# by the package or by Ansible; without it the helper detects one.

set -u

# The caller's PATH first (root's own, or the service user's when run directly),
# then the system directories that minimal environments such as cron leave out.
PATH=${PATH:+$PATH:}/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
LC_ALL=C
export PATH LC_ALL

PACKAGE=suricatavel-agent
SYSTEMD_UNIT=suricatavel-agent.service
RC_SERVICE=suricatavel_agent
SUPERVISOR_PROGRAM='suricatavel-agent:*'

fail() {
    echo "$1" >&2
    exit "${2:-1}"
}

has() {
    command -v "$1" >/dev/null 2>&1
}

# Runs a command, stopping it after the given number of seconds when timeout(1) exists.
limited() {
    seconds=$1
    shift
    if has timeout; then
        timeout "$seconds" "$@"
    else
        "$@"
    fi
}

manager_file() {
    if [ -n "${SURICATAVEL_AGENT_SERVICE_MANAGER_FILE:-}" ]; then
        echo "$SURICATAVEL_AGENT_SERVICE_MANAGER_FILE"
    elif [ "$(uname -s)" = FreeBSD ]; then
        echo /usr/local/etc/suricatavel-agent/service-manager
    else
        echo /etc/suricatavel-agent/service-manager
    fi
}

detect_manager() {
    file=$(manager_file)
    if [ -r "$file" ]; then
        configured=$(sed -n '1{s/[[:space:]]//g;p;}' "$file")
        case "$configured" in
            systemd|supervisor|rcd) echo "$configured"; return 0 ;;
            *) fail "Unknown service manager '$configured' in $file." 65 ;;
        esac
    fi

    if [ "$(uname -s)" = FreeBSD ]; then
        echo rcd
    elif [ -d /run/systemd/system ] && has systemctl \
        && systemctl list-unit-files "$SYSTEMD_UNIT" 2>/dev/null | grep -q "^$SYSTEMD_UNIT"; then
        echo systemd
    elif has supervisorctl; then
        echo supervisor
    else
        echo none
    fi
}

supervisor_config() {
    for config in /etc/supervisor/supervisord.conf /etc/supervisord.conf; do
        if [ -f "$config" ]; then
            echo "$config"
            return 0
        fi
    done
}

supervisorctl_run() {
    config=$(supervisor_config)
    if [ -n "$config" ]; then
        limited 60 supervisorctl -c "$config" "$@"
    else
        limited 60 supervisorctl "$@"
    fi
}

supervisor_daemon() {
    if [ -f /etc/supervisord.conf ] && [ ! -f /etc/supervisor/supervisord.conf ]; then
        echo supervisord
    else
        echo supervisor
    fi
}

service_operation() {
    action=$1
    case "$action" in
        status|start|stop|restart) ;;
        *) fail "Unknown service operation '$action'." 64 ;;
    esac

    case "$(detect_manager)" in
        systemd)
            if [ "$action" = status ]; then
                systemctl show "$SYSTEMD_UNIT" --timestamp=unix \
                    --property=ActiveState,SubState,MainPID,ExecMainStartTimestamp
            else
                limited 120 systemctl "$action" "$SYSTEMD_UNIT"
            fi
            ;;
        supervisor)
            if [ "$action" = status ]; then
                supervisorctl_run status
            else
                supervisorctl_run "$action" "$SUPERVISOR_PROGRAM"
            fi
            ;;
        rcd)
            limited 120 service "$RC_SERVICE" "$action"
            ;;
        *)
            fail 'No service manager found for the agent.' 69
            ;;
    esac
}

# The supervisord daemon itself; systemd and rc.d are always there.
daemon_operation() {
    action=$1
    case "$action" in
        running|start|ready) ;;
        *) fail "Unknown daemon operation '$action'." 64 ;;
    esac

    [ "$(detect_manager)" = supervisor ] || return 0

    case "$action" in
        running) service "$(supervisor_daemon)" status ;;
        start) limited 60 service "$(supervisor_daemon)" start ;;
        ready) supervisorctl_run version ;;
    esac
}

package_operation() {
    action=$1
    version=${2:-}

    if [ -n "$version" ]; then
        case "$version" in
            *[!A-Za-z0-9.+:~_-]*) fail "Invalid package version '$version'." 64 ;;
        esac
    fi

    case "$action" in
        refresh)
            if has apt-get; then
                limited 300 apt-get update -qq
            elif has dnf; then
                limited 300 dnf makecache -q
            elif has yum; then
                limited 300 yum makecache -q
            elif has pkg; then
                limited 300 pkg update -q
            else
                fail 'No supported package manager found.' 69
            fi
            ;;
        available)
            if has apt-cache; then
                limited 60 apt-cache policy "$PACKAGE"
            elif has dnf; then
                limited 60 dnf info "$PACKAGE" -C
            elif has yum; then
                limited 60 yum info "$PACKAGE" -C
            elif has pkg; then
                limited 60 pkg rquery '%v' "$PACKAGE"
            else
                fail 'No supported package manager found.' 69
            fi
            ;;
        install)
            if has apt-get; then
                DEBIAN_FRONTEND=noninteractive
                export DEBIAN_FRONTEND
                if [ -n "$version" ]; then
                    limited 600 apt-get install -y --allow-downgrades "$PACKAGE=$version"
                else
                    limited 600 apt-get install -y "$PACKAGE"
                fi
            elif has dnf || has yum; then
                tool=dnf
                has dnf || tool=yum
                if [ -n "$version" ]; then
                    limited 600 "$tool" downgrade -y "$PACKAGE-$version" || limited 600 "$tool" install -y "$PACKAGE-$version"
                else
                    limited 600 "$tool" upgrade -y "$PACKAGE"
                fi
            elif has pkg; then
                if [ -n "$version" ]; then
                    limited 600 pkg install -y -f "$PACKAGE"
                else
                    limited 600 pkg upgrade -y "$PACKAGE"
                fi
            else
                fail 'No supported package manager found.' 69
            fi
            ;;
        *)
            fail "Unknown package operation '$action'." 64
            ;;
    esac
}

dispatch() {
    [ $# -ge 1 ] || fail 'Missing operation.' 64

    operation=$1
    shift

    case "$operation:$#" in
        manager:0) detect_manager ;;
        service:1) service_operation "$1" ;;
        daemon:1) daemon_operation "$1" ;;
        package:1|package:2) package_operation "$@" ;;
        *) fail "Unknown operation '$operation' with $# argument(s)." 64 ;;
    esac
}

serve() {
    while IFS= read -r request; do
        set -f
        # Word splitting is intended: a request is an operation and its arguments.
        # shellcheck disable=SC2086
        set -- $request
        set +f
        output=$( (dispatch "$@") 2>&1 </dev/null )
        status=$?
        printf '%s %s\n%s' "$status" "${#output}" "$output"
    done
}

if [ "${1:-}" = --serve ]; then
    [ $# -eq 1 ] || fail 'Usage: suricatavel-agent-helper --serve' 64
    serve
else
    dispatch "$@"
fi
