#!/usr/bin/sh
#
# Suricatavel privileged helper
#
# The only part of Suricatavel that may run as root. It never runs PHP: it runs a
# fixed set of supervisor and package operations, and checks every argument.
#
# Usage:
#   suricatavel-helper service status
#   suricatavel-helper service start|stop|restart <program>...
#   suricatavel-helper service reread|update
#   suricatavel-helper daemon running|start|ready
#   suricatavel-helper package refresh
#   suricatavel-helper package install [version]
#   suricatavel-helper --serve
#
# A program is suricatavel:*, suricatavel:<worker> or suricatavel:<worker>_<NN>.
#
# With --serve it answers the requests of the CLI wrapper: one request per line on
# standard input ("service restart suricatavel:web"), and for each one
# "<exit code> <bytes>\n" followed by that many bytes of output on standard output.

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
MAX_PROGRAMS=32

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
}

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() {
    seconds=$1
    shift
    config=$(supervisor_config)
    if [ -n "$config" ]; then
        limited "$seconds" supervisorctl -c "$config" "$@"
    else
        limited "$seconds" supervisorctl "$@"
    fi
}

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

check_program() {
    case "$1" in
        suricatavel:\*) return 0 ;;
        suricatavel:*[!a-z0-9_]*) ;;
        suricatavel:[a-z]*) return 0 ;;
    esac
    fail "Invalid program '$1'." 64
}

service_operation() {
    action=$1
    shift

    case "$action" in
        status|reread|update)
            [ $# -eq 0 ] || fail "Service '$action' takes no programs." 64
            if [ "$action" = status ]; then
                supervisorctl_run 60 status
            else
                supervisorctl_run 120 "$action"
            fi
            ;;
        start|stop|restart)
            [ $# -ge 1 ] && [ $# -le "$MAX_PROGRAMS" ] || fail "Service '$action' takes 1 to $MAX_PROGRAMS programs." 64
            for program in "$@"; do
                check_program "$program"
            done
            supervisorctl_run 300 "$action" "$@"
            ;;
        *)
            fail "Unknown service operation '$action'." 64
            ;;
    esac
}

daemon_operation() {
    case "$1" in
        running) service "$(supervisor_daemon)" status ;;
        start) limited 60 service "$(supervisor_daemon)" start ;;
        ready) supervisorctl_run 30 version ;;
        *) fail "Unknown daemon operation '$1'." 64 ;;
    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
            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 1800 apt-get install -y --allow-downgrades "$PACKAGE=$version"
                else
                    limited 1800 apt-get install -y "$PACKAGE"
                fi
            elif has dnf || has yum; then
                tool=dnf
                has dnf || tool=yum
                if [ -n "$version" ]; then
                    limited 1800 "$tool" downgrade -y "$PACKAGE-$version" || limited 1800 "$tool" install -y "$PACKAGE-$version"
                else
                    limited 1800 "$tool" 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
        service:0|daemon:0|package:0) fail "Operation '$operation' needs an action." 64 ;;
        service:*) service_operation "$@" ;;
        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-helper --serve' 64
    serve
else
    dispatch "$@"
fi
