#!/bin/sh

# dash, busybox ash and bash all have "local".  "local x=$(cmd)" keeps
# the exit status of cmd out of set -e on purpose in this script.
# shellcheck disable=SC3043,SC2155

#####################################################################
#
# Copyright (C) NGINX, Inc.
# Author: NGINX Unit Team, F5 Inc.
# Copyright 2024, Alejandro Colomar <alx@kernel.org>
#
#####################################################################


set -euf;

# pipefail is not in POSIX; use it when the shell supports it.
# shellcheck disable=SC3040
if (set -o pipefail) 2>/dev/null; then
    set -o pipefail;
fi;


export LC_ALL=C

dry_run='no';

help_unit()
{
    cat <<__EOF__ ;
SYNOPSIS
        $0 [-h[h]] COMMAND [ARGS]

    Subcommands
        ├── repo-config  [-h]
        └── welcome      [-hn]

DESCRIPTION
        This script simplifies installing and configuring a FreeUnit server
        for first-time users.

        Run '$0 COMMAND -h' for more information on a command.

COMMANDS
        repo-config
                Print where FreeUnit packages are published.  No package
                repository is configured.

        welcome
                Create an initial configuration to serve a welcome web page
                with FreeUnit.

OPTIONS
        -h, --help
                Print this help.

        -hh, --help-more
                Print help for more (advanced) commands.

__EOF__
}

help_more_unit()
{
    cat <<__EOF__ ;
SYNOPSIS
        $0 [-h[h]] COMMAND [ARGS]

    Subcommands
        ├── cmd          [-h]
        ├── ctl          [-h] [-s SOCK] SUBCOMMAND [ARGS]
        │   ├── edit     [-h] PATH
        │   ├── http     [-h] [-c CURLOPT] METHOD PATH
        │   └── insert   [-h] PATH INDEX
        ├── freeport     [-h]
        ├── json-ins     [-hn] JSON INDEX
        ├── os-probe     [-h]
        ├── ps           [-h] [-t TYPE]
        ├── repo-config  [-h]
        ├── restart      [-hls]
        ├── sock         [-h] SUBCOMMAND [ARGS]
        │   ├── filter   [-chs]
        │   └── find     [-h]
        └── welcome      [-hn]

DESCRIPTION
        This script simplifies installing and configuring
        a FreeUnit server for first-time users.

        Run '$0 COMMAND -h' for more information on a command.

COMMANDS
        cmd     Print the invocation line of unitd(8).

        ctl     Control a running unitd(8) instance via its control API socket.

        freeport
                Print an available TCP port.

        json-ins
                Insert a JSON element read from standard input into a JSON
                array read from a file at a given INDEX.

        os-probe
                Probe the OS and print details about its version.

        ps      List unitd(8) processes.

        repo-config
                Print where FreeUnit packages are published.  No
                package repository is configured.

        restart
                Restart all running unitd(8) instances.

        sock    Print the control API socket address.

        welcome
                Create an initial configuration to serve a welcome web page
                with FreeUnit.

OPTIONS
        -h, --help
                Print basic help (some commands are hidden).

        -hh, --help-more
                Print the hidden help with more commands.

__EOF__
}

info()
{
    >&2 echo "$(basename "$0"): info: $*";
}

warn()
{
    >&2 echo "$(basename "$0"): error: $*";
}

err()
{
    >&2 echo "$(basename "$0"): error: $*";
    exit 1;
}

dry_run_echo()
{
    if test "$dry_run" = "yes"; then
        echo "$*";
    fi;
}

dry_run_eval()
{
    if test "$dry_run" = "yes"; then
        echo "    $*";
    else
        eval "$*";
    fi;
}

# POSIX has no way to query a trap (trap -p is a bash/ksh extension), so the
# command to run is kept in trap_cmd when the trap is set.
run_trap()
{
    eval "${trap_cmd-}";
    trap - "$1";
}


help_unit_cmd()
{
    cat <<__EOF__ ;
SYNOPSIS
        $0 cmd [-h]

DESCRIPTION
        Print the invocation line of running unitd(8) instances.

OPTIONS
        -h, --help
                Print this help.

__EOF__
}


unit_cmd()
{
    while test $# -ge 1; do
        case "$1" in
        -h | --help)
            help_unit_cmd;
            exit 0;
            ;;
        -*)
            err "cmd: $1: Unknown option.";
            ;;
        *)
            err "cmd: $1: Unknown argument.";
            ;;
        esac;
        shift;
    done;

    me=$(id -u);
    unit_ps -t m \
    | while read -r _pid _rest; do
        # Trust only a "unit: main" owned by the superuser or by us: it never
        # drops privileges, so a decoy owned by another user is an attacker's.
        # The filter lives here, not in unit_ps(), because this is the only
        # path whose bracketed argv is later eval'd (unit_restart) or run
        # (unit_sock_find); the public "unit_ps" listing stays complete.
        _owner=$(ps -o uid= -p "$_pid" 2> /dev/null | tr -dc '0-9');
        if [ -n "$_owner" ] && { [ "$_owner" = 0 ] || [ "$_owner" = "$me" ]; }; then
            printf '%s %s\n' "$_pid" "$_rest";
        fi;
    done \
    | sed 's/.*\[\(.*\)].*/\1/';
}


help_unit_ctl()
{
    cat <<__EOF__ ;
SYNOPSIS
        $0 ctl [-h] [-s SOCK] SUBCOMMAND [ARGS]

    Subcommands
        ├── edit    [-h] PATH
        ├── http    [-h] [-c CURLOPT] METHOD PATH
        └── insert  [-h] PATH INDEX

DESCRIPTION
        Control a running unitd(8) instance through its control API socket.

        Run '$0 ctl SUBCOMMAND -h' for more information on a
        subcommand.

SUBCOMMANDS
        edit    Edit the unitd(8) configuration with an editor.

        http    Send an HTTP request to the control API socket.

        insert  Insert an element at the specified index into an array in the
                JSON configuration.

OPTIONS
        -h, --help
                Print this help.

        -s, --sock SOCK
                Use SOCK as the control API socket address.  If not specified,
                the script tries to find it.  This value is used by subcommands.

                The socket can be a tcp(7) socket or a unix(7) socket; in
                the case of a unix(7) socket, it can exist locally or on
                a remote machine, accessed through ssh(1).  Accepted syntax
                for SOCK:

                    unix:/path/to/control.sock
                    ssh://[user@]host[:port]/path/to/control.sock
                    [http[s]://]host[:port]

                The last form is less secure than the first two; have a look:
                <https://docs.freeunit.org/howto/security/#secure-socket-and-state>

ENVIRONMENT
        Options take precedence over their equivalent environment variables;
        if both are specified, the command-line option is used.

        UNIT_CTL_SOCK
                Equivalent to the option -s (--sock).

__EOF__
}


unit_ctl()
{

    if test -n "${UNIT_CTL_SOCK+x}"; then
        local sock="$UNIT_CTL_SOCK";
    fi;

    while test $# -ge 1; do
        case "$1" in
        -h | --help)
            help_unit_ctl;
            exit 0;
            ;;
        -s | --sock)
            if ! test $# -ge 2; then
                err "ctl: $1: Missing argument.";
            fi;
            local sock="$2";
            shift;
            ;;
        -*)
            err "ctl: $1: Unknown option.";
            ;;
        *)
            break;
            ;;
        esac;
        shift;
    done;

    if test ! $# -ge 1; then
        err 'ctl: Missing subcommand.';
    fi;

    if ! test -n "${sock+x}"; then
        local sock="$(unit_sock_find)";
    fi;

    if echo $sock | grep '^ssh://' >/dev/null; then
        local remote="$(echo $sock | sed 's,\(ssh://[^/]*\).*,\1,')";
        local sock="$(echo $sock | sed 's,ssh://[^/]*\(.*\),unix:\1,')";

        local remote_sock="$(echo "$sock" | unit_sock_filter -s)";
        local local_sock="$(mktemp -u -p /var/run/unit/)";
        local ssh_ctrl="$(mktemp -u -p /var/run/unit/)";

        mkdir -p /var/run/unit/;

        ssh -fMNnT -S "$ssh_ctrl" \
                   -o 'ExitOnForwardFailure yes' \
                   -L "$local_sock:$remote_sock" "$remote";

        trap_cmd="ssh -S '$ssh_ctrl' -O exit '$remote' 2>/dev/null;
                  unlink '$local_sock';";
        # The variables expand now, on purpose: they are local.
        # shellcheck disable=SC2064
        trap "$trap_cmd" EXIT;

        sock="unix:$local_sock";
    fi;

    case $1 in
    edit)
        shift;
        unit_ctl_edit ---s "$sock" "$@";
        ;;
    http)
        shift;
        unit_ctl_http ---s "$sock" "$@";
        ;;
    insert)
        shift;
        unit_ctl_insert ---s "$sock" "$@";
        ;;
    *)
        err "ctl: $1: Unknown argument.";
        ;;
    esac;

    if test -n "${remote+x}"; then
        run_trap EXIT;
    fi;
}


help_unit_ctl_edit()
{
    cat <<__EOF__ ;
SYNOPSIS
        $0 ctl [CTL-OPTS] edit [-h] PATH

DESCRIPTION
        Edit the JSON configuration with an editor.  The current configuration
        is downloaded into a temporary file, open with the editor, and then
        sent back to the control API socket.

        The following editors are tried in this order of preference: \$VISUAL,
        \$EDITOR, editor(1), vi(1), vim(1), ed(1).


OPTIONS
        -h, --help
                Print this help.

ENVIRONMENT
        VISUAL
        EDITOR
                See environ(7).

SEE ALSO
        $0 ctl http -h;

        update-alternatives(1)

__EOF__
}


unit_ctl_edit()
{
    while test $# -ge 1; do
        case "$1" in
        -h | --help)
            help_unit_ctl_edit;
            exit 0;
            ;;
        ---s | ----sock)
            local sock="$2";
            shift;
            ;;
        -*)
            err "ctl: edit: $1: Unknown option.";
            ;;
        *)
            break;
            ;;
        esac;
        shift;
    done;

    if ! test $# -ge 1; then
        err 'ctl: edit: PATH: Missing argument.';
    fi;
    local req_path="$1";

    suffix=$(echo "$req_path" \
        | sed 's%^/js_modules/.*%.js%' \
        | sed 's%^/config\>.*%.json%' \
        | sed 's%^/.*%.txt%');
    tmp=$(mktemp "${TMPDIR:-/tmp}/unit-ctl.XXXXXX");
    mv "$tmp" "$tmp$suffix";
    tmp="$tmp$suffix";

    unit_ctl_http ---s "$sock" -c --no-progress-meter GET "$req_path" \
            </dev/null >"$tmp";

    $(
        if test -n "${VISUAL+x}" && test -n "$VISUAL"; then
            printf '%s\n' "$VISUAL";
        elif test -n "${EDITOR+x}" && test -n "$EDITOR"; then
            printf '%s\n' "$EDITOR";
        elif command -v editor; then
            :
        elif command -v vi; then
            :
        elif command -v vim; then
            :
        else
            echo ed;
        fi;
    ) "$tmp";

    unit_ctl_http ---s "$sock" PUT "$req_path" <"$tmp" \
    || {
        rc=$?;
        info "ctl: edit: Invalid configuration saved in <$tmp>.";
        exit "$rc";
    };
}


help_unit_ctl_http()
{
    cat <<__EOF__ ;
SYNOPSIS
        $0 ctl [CTL-OPTS] http [-h] [-c CURLOPT] METHOD PATH

DESCRIPTION
        Send an HTTP request to the unitd(8) control API socket.

        The payload is read from standard input.

OPTIONS
        -c, --curl CURLOPT
                Pass CURLOPT as an option to curl.  This script is implemented
                in terms of curl(1), so it's useful to be able to tweak its
                behavior.  The option can be cumulatively used multiple times
                (the result is also appended to UNIT_CTL_HTTP_CURLOPTS).

        -h, --help
                Print this help.

ENVIRONMENT
        UNIT_CTL_HTTP_CURLOPTS
                Equivalent to the option -c (--curl).

EXAMPLES
        $0 ctl http -c --no-progress-meter GET /config >tmp;

SEE ALSO
        <https://docs.freeunit.org/controlapi/#api-manipulation>

__EOF__
}


unit_ctl_http()
{
    local curl_options="${UNIT_CTL_HTTP_CURLOPTS:-}";

    while test $# -ge 1; do
        case "$1" in
        -c | --curl)
            if ! test $# -ge 2; then
                err "ctl: http: $1: Missing argument.";
            fi;
            curl_options="$curl_options $2";
            shift;
            ;;
        -h | --help)
            help_unit_ctl_http;
            exit 0;
            ;;
        ---s | ----sock)
            local sock="$2";
            shift;
            ;;
        -*)
            err "ctl: http: $1: Unknown option.";
            ;;
        *)
            break;
            ;;
        esac;
        shift;
    done;

    if ! test $# -ge 1; then
        err 'ctl: http: METHOD: Missing argument.';
    fi;
    local method="$1";

    if ! test $# -ge 2; then
        err 'ctl: http: PATH: Missing argument.';
    fi;
    local req_path="$2";

    # The filter prints "--unix-socket <path> <url>": split it into words.
    # shellcheck disable=SC2046
    curl --fail-with-body $curl_options -X $method -d@- \
            $(echo "$sock" | unit_sock_filter -c)${req_path};
}


help_unit_ctl_insert()
{
    cat <<__EOF__ ;
SYNOPSIS
        $0 ctl [CTL-OPTS] insert [-h] PATH INDEX

DESCRIPTION
        Insert an element at the specified position (INDEX) into the JSON array
        located at PATH in unitd(8) control API.

        The new element is read from standard input.

OPTIONS
        -h, --help
                Print this help.

SEE ALSO
        $0 ctl http -h;

__EOF__
}


unit_ctl_insert()
{
    while test $# -ge 1; do
        case "$1" in
        -h | --help)
            help_unit_ctl_insert;
            exit 0;
            ;;
        ---s | ----sock)
            local sock="$2";
            shift;
            ;;
        -*)
            err "ctl: insert: $1: Unknown option.";
            ;;
        *)
            break;
            ;;
        esac;
        shift;
    done;

    if ! test $# -ge 1; then
        err 'ctl: insert: PATH: Missing argument.';
    fi;
    local req_path="$1";

    if ! test $# -ge 2; then
        err 'ctl: insert: INDEX: Missing argument.';
    fi;
    local idx="$2";

    local old="$(mktemp)";

    unit_ctl_http ---s "$sock" -c --no-progress-meter GET "$req_path" \
            </dev/null >"$old";

    unit_json_ins "$old" "$idx" \
    | unit_ctl_http ---s "$sock" PUT "$req_path";
}


help_unit_ctl_welcome()
{
    cat <<__EOF__ ;
SYNOPSIS
        $0 welcome [-hn]

DESCRIPTION
        This script tests a FreeUnit installation by creating an initial
        configuration and serving a welcome web page.  Recommended for
        first-time users.

OPTIONS
        -h, --help
                Print this help.

        -n, --dry-run
                Dry run.  Print the commands to be run instead of actually
                running them.  Each command is preceded by a line explaining
                what it does.

__EOF__
}


unit_ctl_welcome()
{
    while test $# -ge 1; do
        case "$1" in
        -f | --force)
            local force='yes';
            ;;
        -h | --help)
            help_unit_ctl_welcome;
            exit 0;
            ;;
        -n | --dry-run)
            dry_run='yes';
            ;;
        -*)
            err "welcome: $1: Unknown option.";
            ;;
        *)
            err "welcome: $1: Unknown argument.";
            ;;
        esac;
        shift;
    done;

    command -v curl >/dev/null \
    || err 'welcome: curl(1) not found in PATH.  It must be installed to run this script.';

    www='/srv/www/unit/index.html';
    if test -e "$www" && ! test -n "${force+x}" || ! test -w /srv; then
        www="$HOME/srv/www/unit/index.html";
    fi;
    if test -e "$www" && ! test -n "${force+x}"; then
        www="$(mktemp)";
        mv "$www" "$www.html";
        www="$www.html"
    fi;

    nprocs=$(unit_ps -t m | wc -l) \
    || :;

    if test 0 -eq "$nprocs"; then
        warn "welcome: FreeUnit isn't running.";
        warn 'For help with starting FreeUnit, see:';
        err  "  <https://docs.freeunit.org/installation/#startup-and-shutdown>";
    elif test 1 -ne "$nprocs"; then
        err 'welcome: Only one FreeUnit instance should be running.';
    fi;

    local sock="$(unit_sock_find)";
    local curl_opt="$(unit_sock_find | unit_sock_filter -c)";

    curl $curl_opt/ >/dev/null 2>&1 \
    || err "welcome: Can't reach the control API socket.";

    if ! test -n "${force+x}"; then
        cmd=$(unit_cmd);

        # Check unitd is not configured already.
        conffile=$(echo "$cmd" \
        | if grep '\--statedir' >/dev/null; then
            echo "$cmd" \
            | sed 's/ --/\n--/g' \
            | grep '\--statedir' \
            | cut -d' ' -f2;
        else
            $cmd --help \
            | sed -n '/\--statedir/,+1p' \
            | grep 'default:' \
            | sed 's/ *default: "\(.*\)"/\1/';
        fi \
        | sed 's,$,/conf.json,') \
        || :;

        if test -e $conffile; then
            if ! unit_ctl_http ---s "$sock" 'GET' '/config' </dev/null 2>/dev/null | grep -q '^{}.\?$';  # The '.\?' is for the possible carriage return.
            then
                warn 'welcome: FreeUnit is already configured.  To overwrite';
                err  'its current configuration, run the script again with --force.';
            fi;
        fi;
    fi;

    port=$(
        unit_freeport \
        || err "welcome: Can't find an available port.";
    );

    dry_run_echo 'Create a file to serve:';
    dry_run_eval "mkdir -p $(dirname $www);";
    dry_run_eval "tee '$www' >/dev/null"' <<__EOF__;
        <!DOCTYPE html>
        <html>
            <head>
                <title>Welcome to FreeUnit</title>
                <style type="text/css">
                    body { background: white; color: black; font-family: sans-serif; margin: 2em; line-height: 1.5; }
                    h1,h2 { color: #00974d; }
                    li { margin-bottom: 0.5em; }
                    pre { background-color: beige; padding: 0.4em; }
                    hr { margin-top: 2em; border: 1px solid #00974d; }
                    .indent { margin-left: 1.5em; }
                </style>
            </head>
            <body>
                <h1>Welcome to FreeUnit</h1>
                <p>Congratulations! FreeUnit is installed and running.</p>
                <h3>Useful Links</h3>
                <ul>
                    <li><b><a href="https://docs.freeunit.org/configuration/">https://docs.freeunit.org/configuration/</a></b><br>
                        To get started with Unit, see the <em>Configuration</em> docs, starting with
                        the <em>Quick Start</em> guide.</li>
                    <li><b><a href="https://github.com/freeunitorg/freeunit">https://github.com/freeunitorg/freeunit</a></b><br>
                        See our GitHub repo to browse the code, contribute, or seek help from the
                        <a href="https://github.com/freeunitorg/freeunit#community">community</a>.</li>
                </ul>

                <h2>Next steps</h2>

                <h3>Check Current Configuration</h3>
                <div class="indent">
                <p>Unit'"'"'s control API is currently listening for configuration changes
                   on the '"$(unit_sock_find | grep -q '^unix:' && echo '<a href="https://en.wikipedia.org/wiki/Unix_domain_socket">Unix socket</a>' || echo 'socket')"' at
                   <b>'"$(unit_sock_find)"'</b><br>
                   To see the current configuration:</p>
                <pre>'"${SUDO_USER:+sudo }"'curl '"$curl_opt"'/config</pre>
                </div>

                <h3>Change Listener Port</h3>
                <div class="indent">
                <p>This page is served over a random TCP high port.  To choose the default HTTP port (80),
                   replace the <b>"listeners"</b> object:</p>
                <pre>echo '"'"'{"*:80": {"pass": "routes"}}'"'"' | '"${SUDO_USER:+sudo }"'curl -X PUT -d@- '"$curl_opt"'/config/listeners</pre>
                Then remove the port number from the address bar and reload the page.
                </div>

                <hr>
                <p><a href="https://docs.freeunit.org/">FreeUnit &mdash; the universal web app server</a><br>
                FreeUnit Community &copy; 2026</p>
            </body>
        </html>
__EOF__';
    dry_run_echo;
    dry_run_echo 'Give it appropriate permissions:';
    dry_run_eval "chmod 644 '$www';";
    dry_run_echo;

    dry_run_echo 'Configure unitd:'
    dry_run_eval "cat <<__EOF__ \\
        | sed 's/8080/$port/' \\
        | curl -X PUT -d@- $curl_opt/config;
        {
            \"listeners\": {
                \"*:8080\": {
                    \"pass\": \"routes\"
                }
            },
            \"routes\": [{
                \"action\": {
                    \"share\": \"$www\"
                }
            }]
        }
__EOF__";

    dry_run_echo;

    echo;
    echo 'You may want to try the following commands now:';
    echo;
    echo 'Check out current unitd configuration:';
    echo "    ${SUDO_USER:+sudo} curl $curl_opt/config";
    echo;
    echo 'Browse the welcome page:';
    echo "    curl http://localhost:$port/";
}


help_unit_freeport()
{
    cat <<__EOF__ ;
SYNOPSIS
        $0 freeport [-h]

DESCRIPTION
        Print an available TCP port.

OPTIONS
        -h, --help
                Print this help.

__EOF__
}


unit_freeport()
{
    while test $# -ge 1; do
        case "$1" in
        -h | --help)
            help_unit_freeport;
            exit 0;
            ;;
        -*)
            err "freeport: $1: Unknown option.";
            ;;
        *)
            err "freeport: $1: Unknown argument.";
            ;;
        esac;
        shift;
    done;

    freeport="$(mktemp -t freeport-XXXXXX)";

    cat <<__EOF__ \
    | cc -x c -o $freeport -;
        #include <netinet/in.h>
        #include <stdio.h>
        #include <stdlib.h>
        #include <strings.h>
        #include <sys/socket.h>
        #include <unistd.h>


        int32_t get_free_port(void);


        int
        main(void)
        {
            int32_t  port;

            port = get_free_port();
            if (port == -1)
                exit(EXIT_FAILURE);

            printf("%d\n", port);
            exit(EXIT_SUCCESS);
        }


        int32_t
        get_free_port(void)
        {
            int                 sfd;
            int32_t             port;
            socklen_t           len;
            struct sockaddr_in  addr;

            port = -1;

            sfd = socket(PF_INET, SOCK_STREAM, 0);
            if (sfd == -1) {
                perror("socket()");
                return -1;
            }

            bzero(&addr, sizeof(addr));
            addr.sin_family = AF_INET;
            addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
            addr.sin_port = htons(0);  // random port

            len = sizeof(addr);
            if (bind(sfd, (struct sockaddr *) &addr, len)) {
                perror("bind()");
                goto fail;
            }

            if (getsockname(sfd, (struct sockaddr *) &addr, &len)) {
                perror("getsockname()");
                goto fail;
            }

            port = ntohs(addr.sin_port);

        fail:
            close(sfd);
            return port;
        }
__EOF__

    $freeport;
}


help_unit_json_ins()
{
cat <<__EOF__ ;
SYNOPSIS
        $0 json-ins [-hn] JSON INDEX

ARGUMENTS
        JSON    Path to a JSON file containing a top-level array.

        INDEX   Position in the array to insert the element at.

DESCRIPTION
        Insert a JSON element read from standard input into a JSON array read
        from a file at a given INDEX.

        The resulting array is printed to standard output.

OPTIONS
        -h, --help
                Print this help.

        -n, --dry-run
                Dry run.  Print the command to be run instead of actually
                running it.

__EOF__
}


unit_json_ins()
{
    while test $# -ge 1; do
        case "$1" in
        -h | --help)
            help_unit_json_ins;
            exit 0;
            ;;
        -n | --dry-run)
            dry_run='yes';
            ;;
        -*)
            err "json-ins: $1: Unknown option.";
            ;;
        *)
            break;
            ;;
        esac;
        shift;
    done;

    if ! test $# -ge 1; then
        err 'json-ins: JSON: Missing argument.';
    fi;
    local arr=$1;

    if ! test $# -ge 2; then
        err 'json-ins: INDEX: Missing argument.';
    fi;
    local idx=$2;

    dry_run_eval "(
        jq '.[0:$idx]' <'$arr';
        echo '[';
        jq .;
        echo ']';
        jq '.[$idx:]' <'$arr';
    ) \\
    | sed '/^\[]$/d' \\
    | sed '/^]$/{N;s/^]\n\[$/,/}' \\
    | jq .;"
}


help_unit_os_probe()
{
    cat <<__EOF__ ;
SYNOPSIS
        $0 os-probe [-h]

DESCRIPTION
        This script probes the OS and prints three fields, delimited by ':';
        the first is the package manager, the second is the OS name, the third
        is the OS version.

OPTIONS
        -h, --help
                Print this help.

__EOF__
}


unit_os_probe()
{
    while test $# -ge 1; do
        case "$1" in
        -h | --help)
            help_unit_os_probe;
            exit 0;
            ;;
        -*)
            err "os-probe: $1: Unknown option.";
            ;;
        *)
            err "os-probe: $1: Unknown argument.";
            ;;
        esac;
        shift;
    done;

    local os="$(uname | tr '[:upper:]' '[:lower:]')"

    if [ "$os" != 'linux' ] && [ "$os" != 'freebsd' ]; then
        err "os-probe: The OS isn't Linux or FreeBSD; can't proceed."
    fi

    if [ "$os" = 'linux' ]; then
        if command -v apt-get >/dev/null; then
            local pkgMngr='apt';
        elif command -v dnf >/dev/null; then
            local pkgMngr='dnf';
        elif command -v yum >/dev/null; then
            local pkgMngr='yum';
        else
            local pkgMngr='';
        fi;

        local osRelease='/etc/os-release';

        if [ -f "$osRelease" ]; then
            # The value for the ID and VERSION_ID may or may not be in quotes
            local osName="$(grep "^ID=" "$osRelease" | sed s/\"//g | awk -F= '{ print $2 }' ||:)"
            local osVersion="$(grep '^VERSION_ID=' "$osRelease" | sed s/\"//g | awk -F= '{ print $2 }' || lsb_release -cs)"
        else
            err "os-probe: Unable to determine OS and version, or the OS isn't supported."
        fi
    else
        local pkgMngr='pkg';
        local osName=$os
        local osVersion="$(uname -rs | awk -F '[ -]' '{print $2}' ||:)"
        if [ -z "$osVersion" ]; then
            err 'os-probe: Unable to get the FreeBSD version.'
        fi
    fi

    osName=$(echo "$osName" | tr '[:upper:]' '[:lower:]')
    echo "$pkgMngr:$osName:$osVersion"
}


help_unit_ps()
{
    cat <<__EOF__ ;
SYNOPSIS
        $0 ps [-h] [-t TYPE]

DESCRIPTION
        List unitd(8) processes.

OPTIONS
        -h, --help
                Print this help.

        -t, --type TYPE
                List only processes of type TYPE.  The available types are:

                -  controller (c)
                -  main (m)
                -  router (r)

__EOF__
}


unit_ps()
{
    while test $# -ge 1; do
        case "$1" in
        -h | --help)
            help_unit_ps;
            exit 0;
            ;;
        -t | --type)
            if ! test $# -ge 2; then
                err "ps: $1: Missing argument.";
            fi;
            local type=;
            case "$2" in
            c | controller)
                local type_c='c';
                ;;
            m | main)
                local type_m='m';
                ;;
            r | router)
                local type_r='r';
                ;;
            esac;
            shift;
            ;;
        -*)
            err "ps: $1: Unknown option.";
            ;;
        *)
            err "ps: $1: Unknown argument.";
            ;;
        esac;
        shift;
    done;

    ps awwx \
    | if test -n "${type+x}"; then
        grep ${type_c:+-e 'unit: controller'} \
             ${type_m:+-e 'unit: main'} \
             ${type_r:+-e 'unit: router'};
    else
        grep 'unit: ';
    fi \
    | grep -v grep \
    ||:
}


help_unit_repo_config()
{
    cat <<__EOF__ ;
SYNOPSIS
        $0 repo-config [-h]

DESCRIPTION
        FreeUnit ships as container images: ghcr.io/freeunitorg/freeunit.
        Each GitHub release also has Debian trixie .deb packages:
        https://github.com/freeunitorg/freeunit/releases
        There is no FreeUnit apt or dnf repository yet, so there is no
        repository to configure.  This command prints a notice and does
        nothing else.  The FreeUnit signing key is already
        published: https://freeunit.org/media/keys/6C68B7AA.asc

        On macOS, install from the Homebrew tap:
        brew tap freeunitorg/unit https://github.com/freeunitorg/homebrew-unit
        brew install freeunitorg/unit/unit

        Distro-specific install notes live in pkg/community/ in the
        repository (debian.md, CENTOS.ALMALINUX.md, MACOS.md).

OPTIONS
        -h, --help
                Print this help.

__EOF__
}


unit_repo_config()
{
    while test $# -ge 1; do
        case "$1" in
        -h | --help)
            help_unit_repo_config;
            exit 0;
            ;;
        -*)
            err "repo-config: $1: Unknown option.";
            ;;
        *)
            err "repo-config: $1: Unexpected argument.";
            ;;
        esac;
        shift;
    done;

    info 'FreeUnit ships as container images: ghcr.io/freeunitorg/freeunit.';
    info 'Each GitHub release also has Debian trixie .deb packages:';
    info '  <https://github.com/freeunitorg/freeunit/releases>';
    info 'There is no FreeUnit apt or dnf repository yet; nothing was configured.';
    info 'On macOS, install from the Homebrew tap:';
    info '  brew tap freeunitorg/unit https://github.com/freeunitorg/homebrew-unit';
    info '  brew install freeunitorg/unit/unit';
    info 'The FreeUnit signing key is already published: <https://freeunit.org/media/keys/6C68B7AA.asc>.';
    info 'For distro-specific install notes, see pkg/community/ in the repository:';
    info '  <https://github.com/freeunitorg/freeunit/tree/1.37/pkg/community>';
}


help_unit_restart()
{
    cat <<__EOF__ ;
SYNOPSIS
        $0 restart [-hls]

DESCRIPTION
        Restart all running unitd(8) instances.

OPTIONS
        -h, --help
                Print this help.

        -l, --log
                Reset log file.

        -s, --statedir
                Reset \$statedir.

CAVEATS
        This command will ask for confirmation before removing
        directories; please review those prompts with care, as unknown
        bugs in the command may attempt to wipe your file system.

__EOF__
}


unit_restart()
{
    while test $# -ge 1; do
        case "$1" in
        -h | --help)
            help_unit_restart;
            exit 0;
            ;;
        -l | --log)
            local log_flag='yes';
            ;;
        -s | --statedir)
            local state_flag='yes';
            ;;
        -*)
            err "restart: $1: Unknown option.";
            ;;
        *)
            err "restart: $1: Unknown argument.";
            ;;
        esac;
        shift;
    done;

    local cmds="$(unit_cmd)";

    pkill -e unitd;

    printf '%s\n' "$cmds" \
    | while read -r cmd; do
        if test -n "${log_flag+x}"; then
            (
                echo "$cmd" \
                | grep '\--log' \
                | sed 's/.*--log \+\([^ ]\+\).*/\1/' \
                || eval $cmd --help \
                | grep -A1 '\--log FILE' \
                | grep 'default:' \
                | sed 's/.*"\(.*\)".*/\1/';
            ) \
            | xargs rm -f;
        fi;

        if test -n "${state_flag+x}"; then
            (
                echo "$cmd" \
                | grep '\--statedir' \
                | sed 's/.*--statedir \+\([^ ]\+\).*/\1/' \
                || eval $cmd --help \
                | grep -A1 '\--statedir DIR' \
                | grep 'default:' \
                | sed 's/.*"\(.*\)".*/\1/';
            ) \
            | xargs -I {} find {} -mindepth 1 -maxdepth 1 \
            | xargs rm -rfi;
        fi;

        eval $cmd;
    done;
}


help_unit_sock()
{
    cat <<__EOF__ ;
SYNOPSIS
        $0 sock [-h] SUBCOMMAND [ARGS]

    Subcommands
        ├── filter  [-ch]
        └── find    [-h]

DESCRIPTION
        Print the control API socket address of running unitd(8)
        instances.

        Run '$0 sock SUBCOMMAND -h' for more information on a
        subcommand.

SUBCOMMANDS
        filter  Filter the output of the 'find' subcommand and transform it
                to something suitable for running other commands, such as
                curl(1) or ssh(1).

        find    Find and print the control API socket address of running
                unitd(8) instances.

OPTIONS
        -h, --help
                Print this help.

__EOF__
}


unit_sock()
{
    while test $# -ge 1; do
        case "$1" in
        -h | --help)
            help_unit_sock;
            exit 0;
            ;;
        -*)
            err "sock: $1: Unknown option.";
            ;;
        *)
            break;
            ;;
        esac;
        shift;
    done;

    if ! test $# -ge 1; then
        err 'sock: Missing subcommand.';
    fi;

    case $1 in
    filter)
        shift;
        unit_sock_filter "$@";
        ;;
    find)
        shift;
        unit_sock_find "$@";
        ;;
    *)
        err "sock: $1: Unknown subcommand.";
        ;;
    esac;
}


help_unit_sock_filter()
{
    cat <<__EOF__ ;
SYNOPSIS
        $0 sock filter [-chs]

DESCRIPTION
        Filter the output of the 'sock find' command and transform it to
        something suitable for running other commands, such as
        curl(1) or ssh(1).

OPTIONS
        -c, --curl
                Print an argument suitable for curl(1).

        -h, --help
                Print this help.

        -s, --ssh
                Print a socket address suitable for use in an ssh(1) tunnel.

__EOF__
}


unit_sock_filter()
{
    while test $# -ge 1; do
        case "$1" in
        -c | --curl)
            if test -n "${ssh_flag+x}"; then
                err "sock: filter: $1: Missing argument.";
            fi;
            local curl_flag='yes';
            ;;
        -h | --help)
            help_unit_sock_filter;
            exit 0;
            ;;
        -s | --ssh)
            if test -n "${curl_flag+x}"; then
                err "sock: filter: $1: Missing argument.";
            fi;
            local ssh_flag='yes';
            ;;
        -*)
            err "sock: filter: $1: Unknown option.";
            ;;
        *)
            err "sock: filter: $1: Unknown argument.";
            ;;
        esac;
        shift;
    done;

    while read -r control; do

        if test -n "${curl_flag+x}"; then
            if echo "$control" | grep '^unix:' >/dev/null; then
                unix_socket="$(echo "$control" | sed 's/unix:/--unix-socket /')";
                host='http://localhost';
            else
                unix_socket='';
                host="$control";
            fi;

            echo "$unix_socket $host";

        elif test -n "${ssh_flag+x}"; then
            echo "$control" \
            | sed -e 's,^unix:,,' -e 's,^http://,,' -e 's,^https://,,';

        else
            echo "$control";
        fi;
    done;
}


help_unit_sock_find()
{
    cat <<__EOF__ ;
SYNOPSIS
        $0 sock find [-h]

DESCRIPTION
        Find and print the control API socket address of running
        unitd(8) instances.

OPTIONS
        -h, --help
                Print this help.

__EOF__
}


unit_sock_find()
{
    while test $# -ge 1; do
        case "$1" in
        -h | --help)
            help_unit_sock_find;
            exit 0;
            ;;
        -*)
            err "sock: find: $1: Unknown option.";
            ;;
        *)
            err "sock: find: $1: Unknown argument.";
            ;;
        esac;
        shift;
    done;

    unit_cmd \
    | while read -r cmd; do
        if echo "$cmd" | grep '\--control' >/dev/null; then
            echo "$cmd" \
            | sed 's/ --/\n--/g' \
            | grep '\--control' \
            | cut -d' ' -f2;
        else
            if ! command -v $cmd >/dev/null; then
                local cmd='unitd';
            fi;
            $cmd --help \
            | sed -n '/\--control/,+1p' \
            | grep 'default:' \
            | sed 's/ *default: "\(.*\)"/\1/';
        fi;
    done;
}


while test $# -ge 1; do
    case "$1" in
    -h | --help)
        help_unit;
        exit 0;
        ;;
    -hh | --help-more)
        help_more_unit;
        exit 0;
        ;;
    -*)
        err "$1: Unknown option.";
        ;;
    *)
        break;
        ;;
    esac;
    shift;
done;

if ! test $# -ge 1; then
    err "Missing command.";
fi;

case $1 in
cmd)
    shift;
    unit_cmd "$@";
    ;;
ctl)
    shift;
    unit_ctl "$@";
    ;;
freeport)
    shift;
    unit_freeport "$@";
    ;;
json-ins)
    shift;
    unit_json_ins "$@";
    ;;
os-probe)
    shift;
    unit_os_probe "$@";
    ;;
ps)
    shift;
    unit_ps "$@";
    ;;
repo-config)
    shift;
    unit_repo_config "$@";
    ;;
restart)
    shift;
    unit_restart "$@";
    ;;
sock)
    shift;
    unit_sock "$@";
    ;;
welcome)
    shift;
    unit_ctl_welcome "$@";
    ;;
*)
    err "$1: Unknown command.";
    ;;
esac;
