#!/usr/bin/env bash
# w4os-site: set up the light website of an OpenSimulator grid.
#
#   w4os-site setup [--api <engine API>] [--url <helpers>] [--key <key>] [--grid <nick>] [--title <title>] [--no-mail | --mail]
#       connect the site to the engine API of a grid, at its own address (on the machine of the grid, the one opensim web GRID
#       api serves, proposed), and to its helpers for the blocks (asked when not given); --no-mail on a test site: the engine mails
#       nothing, the confirmation links are shown on the page
#   w4os-site status
#       what the site is connected to, and whether the API answers
#   w4os-site web apache|caddy|nginx [--host <name>[,<name>...]] [--port <port>] [--prefix /<path>] [--install | --vhosts | --modules | --remove]
#       the configuration of a web server for the site (printed; installed and enabled with --install, Apache and Caddy), at the
#       host and the port of the address of the site when not given (localhost on a new site); with --prefix, the site
#       under that path, in a block of its own beside the one of the host, which it never changes (sites/<host>.w4os.caddyfile),
#       with the helpers of the grid of this machine under it; for Apache, in a file of its own (/etc/apache2/w4os/<host>.conf)
#       that one line includes in each site of Apache serving the host (--vhosts: their files, --modules: the modules of Apache
#       it enables, --remove: the lines taken out, the modules it enabled disabled again)
#   w4os-site --version
#       the version of the site

PGM=w4os-site
COMMANDOPTS=setup,status,web
# The help, before bash-helpers, which knows only its own options: the usage of a command, or all of it
if [[ " $* " == *" --help "* || " $* " == *" -h "* ]]; then
    usage=$(sed -n '3,/^$/p' "$0" | sed -n 's/^# \{0,1\}//p')
    if [[ "${1:-}" =~ ^(setup|status|web)$ ]]; then
        awk -v command="w4os-site $1" 'index($0, command) == 3 { on = 1; print; next } /^  w4os-site / { on = 0 } on' <<<"$usage"
    else
        printf '%s\n' "$usage"
    fi
    exit 0
fi
# Sourced before the options of the shell: bash-tools 1.0.9 stops under set -e when gnu-getopt is not where Homebrew puts it
source "$(command -v bash-helpers)"
set -eo pipefail

SHARE=${W4OS_SITE_SHARE:-/usr/share/w4os-site}
# The site, a standard Grav site the web user owns (bin/w4os-site-tree makes it)
ROOT=${W4OS_SITE_ROOT:-/var/lib/w4os/www}
CONFIG="$ROOT/user/config"
KEY_FILE="$ROOT/user/data/w4os/api.json"
OWNER=${W4OS_SITE_OWNER:-}
GROUP=${W4OS_SITE_GROUP:-$OWNER}

# web_account: the account and group of the web server ("user group"), as the engine of the machine resolves them (WebUser and
# WebGroup of w4os.conf, its profile over [Defaults]), read with the engine the site's w4os plugin carries; www-data without them
web_account() {
    local vendor
    for vendor in "$ROOT/user/plugins/w4os/vendor" "${SEED:-$ROOT}/user/plugins/w4os/vendor"; do
        [ -f "$vendor/autoload.php" ] || continue
        ${W4OS_SITE_PHP:-php} -r 'require $argv[1]; $layout = W4OS\Engine\Config\Layout::load(); echo $layout->webUser(), " ", $layout->webGroup(), PHP_EOL;' \
            "$vendor/autoload.php" 2>/dev/null && return
    done
    echo "www-data www-data"
}

# owner: OWNER and GROUP set from the engine's settings, unless the environment gives them
owner() {
    [ -n "$OWNER" ] || read -r OWNER GROUP < <(web_account) || true
}

# engine_api_urls [GRID]: "nick address" of the engine API of each grid of this machine (of GRID alone when given), as opensim web
# GRID api serves it (its port is the grid's): read with the engine installed here, else with the one the site's w4os plugin
# carries; nothing without a grid here, nor for a grid whose API has no port yet
engine_api_urls() {
    local code engine=${W4OS_SITE_ENGINE:-/usr/share/w4os-engine}
    # shellcheck disable=SC2016 # PHP's own variables
    code='foreach (array_slice($argv, 2) as $autoload) { require $autoload; }
        $environment = W4OS\Engine\Runtime\Environment::system(W4OS\Engine\Config\Layout::load());
        $grids = $argv[1] !== "" ? array_filter([W4OS\Engine\Models\Grid::find($environment, $argv[1])]) : W4OS\Engine\Models\Grid::all($environment);
        foreach ($grids as $grid) {
            $port = method_exists($grid, "knownApiPort") ? $grid->knownApiPort() : null;
            $port === null || print($grid->nick() . " http://127.0.0.1:$port/api" . PHP_EOL);
        }'
    if [ -f "$engine/vendor/autoload.php" ]; then
        ${W4OS_SITE_PHP:-php} -r "$code" "${1:-}" "$engine/vendor/autoload.php" 2>/dev/null && return
    fi
    [ ! -f "$ROOT/user/plugins/w4os/vendor/autoload.php" ] ||
        ${W4OS_SITE_PHP:-php} -r "$code" "${1:-}" "$ROOT/vendor/autoload.php" "$ROOT/user/plugins/w4os/vendor/autoload.php" 2>/dev/null || true
}

# The value of a top-level key of a YAML file, quotes removed
yaml_get() {
    [ -f "$1" ] && sed -n "s/^$2:[[:space:]]*//p" "$1" | head -1 | sed "s/^'\(.*\)'\$/\1/; s/^\"\(.*\)\"\$/\1/" || true
}

# Set a top-level key of a YAML file to a quoted string (or as it is, with --raw: true, false, a number)
yaml_set() {
    local raw=
    [ "$1" != --raw ] || { raw=1; shift; }
    local file=$1 key=$2 value=${3//\'/\'\'}
    [ -z "$raw" ] || value=$3
    mkdir -p "$(dirname "$file")"
    touch "$file"
    if grep -q "^$key:" "$file"; then
        local escaped=${value//\\/\\\\}
        escaped=${escaped//&/\\&}
        escaped=${escaped//|/\\|}
        [ -n "$raw" ] || escaped="'$escaped'"
        sed -i.bak "s|^$key:.*|$key: $escaped|" "$file" && rm -f "$file.bak"
    else
        [ -n "$raw" ] || value="'$value'"
        echo "$key: $value" >>"$file"
    fi
}

api_key() {
    [ -f "$KEY_FILE" ] && sed -n 's/.*"api_key"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$KEY_FILE" || true
}

# GET a path of the engine API (its own address) with the key of the site; the body, or nothing
api_get() {
    local api=$1 key=$2 path=$3
    curl -fsS --max-time 15 -H "Authorization: Bearer $key" -H 'Accept: application/vnd.api+json' "${api%/}$path"
}

ask() {
    local prompt=$1 default=${2:-} answer
    [ -t 0 ] || { echo "$default"; return; }
    read -r -p "$prompt${default:+ [$default]}: " answer
    echo "${answer:-$default}"
}

setup() {
    local api= url= key= grid= title= mail=
    while [ $# -gt 0 ]; do
        case $1 in
        --no-mail) mail=false; shift ;;
        --mail) mail=true; shift ;;
        --api) api=$2; shift 2 ;;
        --url) url=$2; shift 2 ;;
        --key) key=$2; shift 2 ;;
        --grid) grid=$2; shift 2 ;;
        --title) title=$2; shift 2 ;;
        *) die "unknown option $1" ;;
        esac
    done
    [ -d "$CONFIG" ] || die "$CONFIG is missing: is the package installed?"
    # The engine API at its own address, never under the helpers: on the machine of the grid, its local listener
    # proposed: the one the site has, else the one of the grid of this machine (of --grid, or the only one), as the engine gives it
    local suggested known=
    suggested=$(yaml_get "$CONFIG/plugins/w4os.yaml" api_url)
    if [ -z "$suggested" ] && [ -z "$api" ]; then
        known=$(engine_api_urls "$grid")
        [ "$(grep -c . <<<"$known")" != 1 ] || suggested=${known#* }
    fi
    local mine='on the machine of the grid, the one opensim web GRID api serves'
    [ -z "$known" ] || mine="on this machine: $(tr '\n' ',' <<<"$known" | sed 's/,$//; s/,/, /g')"
    api=${api:-$(ask "Address of the engine API (https://grid.example.org/api, or $mine)" "$suggested")}
    [ -n "$api" ] || die "the address of the engine API is needed (--api)"
    api=${api%/}
    url=${url:-$(ask 'Address of the helpers of the grid (https://grid.example.org/helpers)' "$(yaml_get "$CONFIG/plugins/w4os.yaml" url)")}
    [ -n "$url" ] || die "the address of the helpers is needed"
    url=${url%/}
    # The key the site kept, while the engine takes it: refused (an engine installed again), a new one is made
    if [ -z "$key" ]; then
        key=$(api_key)
        if [ -n "$key" ] && ! api_get "$api" "$key" /info >/dev/null 2>&1; then
            warning "the engine API refuses the key the site kept: a new one is made"
            key=
        fi
    fi
    # A grid on this machine makes the key itself
    if [ -z "$key" ] && command -v "${W4OS_SITE_OPENSIM:-opensim}" >/dev/null; then
        key=$("${W4OS_SITE_OPENSIM:-opensim}" api-key create "w4os-site $(hostname)" 2>/dev/null | grep -o 'osk_[A-Za-z0-9_-]*' | head -1 || true)
        [ -z "$key" ] || log "made the API key 'w4os-site $(hostname)' of this machine"
    fi
    [ -n "$key" ] || key=$(ask 'API key of the site (opensim api-key create <label>, on the machine of the grid)')
    [ -n "$key" ] || die "the API key is needed"

    local info
    info=$(api_get "$api" "$key" /info) || die "the engine API does not answer at $api with this key"
    local name
    name=$(printf '%s' "$info" | sed -n 's/.*"gridname":"\([^"]*\)".*/\1/p')

    yaml_set "$CONFIG/plugins/w4os.yaml" engine remote
    yaml_set "$CONFIG/plugins/w4os.yaml" api_url "$api"
    yaml_set "$CONFIG/plugins/w4os.yaml" url "$url"
    [ -z "$grid" ] || yaml_set "$CONFIG/plugins/w4os.yaml" grid "$grid"
    [ -z "$mail" ] || yaml_set --raw "$CONFIG/plugins/w4os.yaml" send_mail "$mail"
    # The title the site has, else the name of its grid (the placeholder shipped is no title): the grid info sends ASCII only
    local current
    current=$(yaml_get "$CONFIG/site.yaml" title)
    [ "$current" != 'My grid' ] || current=
    title=${title:-$(ask 'Title of the site' "${current:-$name}")}
    [ -z "$title" ] || yaml_set "$CONFIG/site.yaml" title "$title"
    mkdir -p "$(dirname "$KEY_FILE")"
    printf '{"api_key":"%s"}\n' "$key" >"$KEY_FILE"
    chmod 640 "$KEY_FILE"
    owner
    chown -R "$OWNER:$GROUP" "$CONFIG" "$ROOT/user/data" 2>/dev/null || true
    rm -rf "${W4OS_SITE_CACHE:-$ROOT/cache}"/* 2>/dev/null || true
    success "connected to ${name:-the grid} ($api)"
}

status() {
    local api url key
    api=$(yaml_get "$CONFIG/plugins/w4os.yaml" api_url)
    url=$(yaml_get "$CONFIG/plugins/w4os.yaml" url)
    key=$(api_key)
    echo "site:    $(yaml_get "$CONFIG/site.yaml" title)"
    echo "api:     ${api:-not set}"
    echo "helpers: ${url:-not set}"
    echo "key:     $([ -n "$key" ] && echo set || echo 'not set')"
    [ "$(yaml_get "$CONFIG/plugins/w4os.yaml" send_mail)" != false ] || echo "mail:    off (test site: the links are shown on the page)"
    [ -n "$api" ] && [ -n "$key" ] || die "not connected: w4os-site setup"
    api_get "$api" "$key" /info >/dev/null && echo "api:     answers" || die "api:     does not answer"
    curl -fsS --max-time 15 -o /dev/null "$url/blocks/grid-info" && echo "blocks:  answer" || warning "blocks:  do not answer"
}

# The socket of PHP-FPM, as its pool says it (listen, in /etc/php/<version>/fpm/pool.d, the version of the site's PHP first), whether
# PHP-FPM runs yet or not; else a socket that is there; nothing without PHP-FPM, or with a pool on a TCP port
php_socket() {
    local etc=${W4OS_SITE_PHP_ETC:-/etc/php} version conf listen user socket pass
    version=$(php -r 'echo PHP_MAJOR_VERSION, ".", PHP_MINOR_VERSION;' 2>/dev/null || true)
    owner
    # The site's own pool of the suite first (w4os-site, as the web user), whatever the web server runs as
    for conf in ${version:+"$etc/$version"/fpm/pool.d/w4os-site.conf} $(ls -r "$etc"/*/fpm/pool.d/w4os-site.conf 2>/dev/null); do
        [ -f "$conf" ] || continue
        listen=$(sed -n 's/^[[:space:]]*listen[[:space:]]*=[[:space:]]*\(\/[^[:space:];]*\).*/\1/p' "$conf" | head -1)
        [ -z "$listen" ] || { echo "$listen" && return; }
    done
    # The pool of the web user first, else another one, never the suite's: the engine API runs as the user of the grid, with its
    # rights, and the helpers have theirs
    for pass in web other; do
        # shellcheck disable=SC2012 # the newest version first; their names have no space
        for conf in ${version:+"$etc/$version"/fpm/pool.d/*.conf} $(ls -r "$etc"/*/fpm/pool.d/*.conf 2>/dev/null); do
            [ -f "$conf" ] || continue
            listen=$(sed -n 's/^[[:space:]]*listen[[:space:]]*=[[:space:]]*\(\/[^[:space:];]*\).*/\1/p' "$conf" | head -1)
            [ -n "$listen" ] && [[ $listen != */w4os-api.sock && $listen != */w4os-helpers.sock && $listen != */w4os-site.sock ]] || continue
            user=$(sed -n 's/^[[:space:]]*user[[:space:]]*=[[:space:]]*\([^[:space:];]*\).*/\1/p' "$conf" | head -1)
            [ "$pass" = other ] || [ "$user" = "$OWNER" ] || continue
            echo "$listen" && return
        done
    done
    for socket in /run/php/php-fpm.sock /run/php/php*-fpm.sock /run/php/php*-fpm-*default.sock; do
        [ -S "$socket" ] && echo "$socket" && return
    done
    return 0
}

# apache_socket SOCKET: the socket of PHP-FPM when the account Apache runs as can reach it (the owner or the group its pool gives
# it, of its envvars); else nothing when Apache has its own PHP (mod_php serves the site then), else the socket as it is
apache_socket() {
    local socket=$1 etc=${W4OS_SITE_APACHE_ETC:-/etc/apache2} conf user group owner listen_group members
    [ -n "$socket" ] || return 0
    user=$(sed -nE 's/^[[:space:]]*export[[:space:]]+APACHE_RUN_USER=["\x27]?([^"\x27[:space:]]+).*/\1/p' "$etc/envvars" 2>/dev/null | tail -1)
    group=$(sed -nE 's/^[[:space:]]*export[[:space:]]+APACHE_RUN_GROUP=["\x27]?([^"\x27[:space:]]+).*/\1/p' "$etc/envvars" 2>/dev/null | tail -1)
    conf=$(grep -lE "^[[:space:]]*listen[[:space:]]*=[[:space:]]*$socket([[:space:];]|$)" "${W4OS_SITE_PHP_ETC:-/etc/php}"/*/fpm/pool.d/*.conf 2>/dev/null | head -1)
    if [ -z "$user" ] || [ -z "$conf" ]; then
        echo "$socket"
        return 0
    fi
    # The owner and group of its socket: listen.owner and listen.group, else the user and group of the pool
    owner=$(sed -nE 's/^[[:space:]]*listen\.owner[[:space:]]*=[[:space:]]*([^[:space:];]+).*/\1/p' "$conf" | head -1)
    [ -n "$owner" ] || owner=$(sed -nE 's/^[[:space:]]*user[[:space:]]*=[[:space:]]*([^[:space:];]+).*/\1/p' "$conf" | head -1)
    listen_group=$(sed -nE 's/^[[:space:]]*listen\.group[[:space:]]*=[[:space:]]*([^[:space:];]+).*/\1/p' "$conf" | head -1)
    [ -n "$listen_group" ] || listen_group=$(sed -nE 's/^[[:space:]]*group[[:space:]]*=[[:space:]]*([^[:space:];]+).*/\1/p' "$conf" | head -1)
    members=" $(id -nG "$user" 2>/dev/null) $group "
    if [ "$owner" = "$user" ] || [[ $members == *" $listen_group "* ]]; then
        echo "$socket"
    elif ! { apache2ctl -M 2>/dev/null || true; } | grep -q 'php[0-9._]*_module'; then
        echo "$socket"
    fi
}

# check_site BASE PORT HOST SOCKET: whether the site answers through PHP on this machine (its page with its title, never PHP's
# source), said either way: what is missing when it does not, with a non-zero status
check_site() {
    local base=$1 port=$2 host=$3 socket=$4 page title
    title=$(yaml_get "$CONFIG/site.yaml" title)
    title=${title//&/&amp;}
    title=${title//\'/&#039;}
    page=$(curl -s --max-time 15 -H "Host: $host" "http://127.0.0.1:$port/" 2>/dev/null || true)
    if grep -q '<title>' <<<"$page" && ! grep -q '<?php' <<<"$page" && { [ -z "$title" ] || grep -qF -- "$title" <<<"$page"; }; then
        success "the site answers at $base/"
        return 0
    elif [ -n "$socket" ] && [ ! -S "$socket" ]; then
        # Its service by the name of its socket (php8.2-fpm), as Debian names both
        local service
        service=$(basename "$socket" .sock)
        [[ $service == php*-fpm ]] || service=php-fpm
        warning "PHP does not run: PHP-FPM is not running ($socket is missing): systemctl start $service, the site is at $base/"
    elif [ -z "$page" ]; then
        warning "Apache does not answer on port $port yet: start it (systemctl start apache2), the site is at $base/"
    elif grep -q '<?php' <<<"$page"; then
        warning "Apache shows the PHP source of the site, it runs no PHP for it: install php-fpm, then w4os-site web apache --install again"
    else
        warning "the site does not answer as it should at $base/: see /var/log/apache2/w4os-site-error.log"
    fi
    return 1
}

# grav_snippet: the file of Grav's rules for Caddy the package ships for the Grav of the site (Grav 1.7 where PHP is older than 8.3)
grav_snippet() {
    if grep -qs "define('GRAV_VERSION', '1\." "$ROOT/system/defines.php"; then
        echo "$SHARE/web/grav17.caddy"
    else
        echo "$SHARE/web/grav.caddy"
    fi
}

# caddy_prefixed ADDRESSES PREFIX SOCKET: the site under PREFIX, in a block of its own whose addresses have the path (Caddy prefers
# it to the block of the host, whatever runs at its root, which it never changes): the helpers of the grid of this machine under
# it (opensim web GRID snippet caddy --prefix), then the site, the prefix stripped; the helpers elsewhere on the host, each exactly
caddy_prefixed() {
    local addresses=$1 prefix=$2 socket=$3 tab=$'\t' list= under= address grid helpers= matcher outdated=
    IFS=, read -ra list <<<"${addresses//, /,}"
    for address in "${list[@]}"; do
        under+="${under:+, }$address$prefix, $address$prefix/*"
    done
    grid=$(yaml_get "$CONFIG/plugins/w4os.yaml" grid)
    if [ -n "$grid" ] && command -v "${W4OS_SITE_OPENSIM:-opensim}" >/dev/null 2>&1; then
        helpers=$("${W4OS_SITE_OPENSIM:-opensim}" web "$grid" snippet caddy --prefix "$prefix" ${socket:+--socket "$socket"} 2>/dev/null | sed -e '/^[[:space:]]*#/d' -e '/^[[:space:]]*$/d' || true)
        # Paths under the prefix, or none: an empty matcher would take every path
        matcher=$(sed -n 's/^@opensim_helpers path[[:space:]]*//p' <<<"$helpers")
        [ -n "$matcher" ] || helpers=
        # A command line before --prefix gives the paths of the root (the prefix itself): never written, said
        local path
        for path in $matcher; do
            [[ $path == "$prefix"/* ]] && continue
            helpers=
            outdated=yes
            warning "the helpers of $grid are not in the file: w4os-cli 3.0.0~beta.4+125 or later gives their paths under $prefix"
            break
        done
    fi
    printf '# The w4os site under %s, beside the site of the host (w4os-site web caddy)\n' "$prefix"
    printf '%s {\n%sencode gzip\n%sredir %s %s/ 308\n' "$under" "$tab" "$tab" "$prefix" "$prefix"
    if [ -n "$helpers" ]; then
        printf '%s# Helpers of the grid %s\n' "$tab" "$grid"
        sed -e "s/^\(.\)/$tab\1/" <<<"$helpers"
    fi
    printf '%s# Website\n%shandle_path %s/* {\n' "$tab" "$tab" "$prefix"
    printf '%s%simport %s %s unix/%s %s/index.php\n%s}\n}\n' "$tab" "$tab" "$(grav_snippet)" "$ROOT" "$socket" "$prefix" "$tab"
    # The helpers of the grid elsewhere on the host: a block of their own for each folder of the root they are in (a file at the
    # root alone), with their handler (the one of opensim web GRID snippet caddy); the block of the host keeps the rest
    local outside= body= places= place addresses
    # Whether or not some are under the prefix (helpers at /helpers, the site under /opensim)
    if [ -n "$grid" ] && [ -z "$outdated" ] && command -v "${W4OS_SITE_OPENSIM:-opensim}" >/dev/null 2>&1; then
        outside=$("${W4OS_SITE_OPENSIM:-opensim}" web "$grid" paths --outside "$prefix" 2>/dev/null || true)
        body=$("${W4OS_SITE_OPENSIM:-opensim}" web "$grid" snippet caddy ${socket:+--socket "$socket"} 2>/dev/null |
            awk '/^handle @opensim_helpers \{/ { inside = 1; next } inside && /^\}/ { inside = 0; next } inside { print }' || true)
    fi
    [ -n "$body" ] || outside=
    while IFS= read -r path; do
        [[ $path == /* && $path != *[[:space:]]* ]] || continue
        place=/$(cut -d/ -f2 <<<"$path")
        # A folder when something is under it (its glob too), else a file at the root
        [[ $path == "$place" ]] || place+=/
        [[ " $places " != *" ${place%/} "* ]] || places=${places/ ${place%/}/}
        [[ " $places " == *" $place "* || " $places " == *" $place/ "* ]] || places+=" $place"
    done <<<"$outside"
    for place in $places; do
        addresses=
        for address in "${list[@]}"; do
            if [[ $place == */ ]]; then
                addresses+="${addresses:+, }$address${place%/}, $address$place*"
            else
                addresses+="${addresses:+, }$address$place"
            fi
        done
        printf '\n# Helpers of the grid %s at %s\n' "$grid" "${place%/}"
        printf '%s {\n%sencode gzip\n%s\n}\n' "$addresses" "$tab" "$body"
    done
}

# caddy_install HOST TEXT: the file of the site in the sites of Caddy (sites/<host>.w4os.caddyfile), checked with the rest, then
# Caddy reloaded; never the file of the host, nor the Caddyfile: a Caddyfile that does not import sites/ is said
caddy_install() {
    local etc=${W4OS_SITE_CADDY_ETC:-/etc/caddy} file said import dir suffix
    require caddy
    # The folder of sites the Caddyfile imports (relative to it, or absolute), the file named as it imports them
    import=$(sed -n 's/^[[:space:]]*import[[:space:]]\{1,\}\([^[:space:]]*\*[^[:space:]]*\).*/\1/p' "$etc/Caddyfile" 2>/dev/null | head -1)
    [ -n "$import" ] ||
        die "the Caddyfile does not import its sites: add the line import sites/* to $etc/Caddyfile, then this command again"
    dir=$(dirname "$import")
    [[ $dir == /* ]] || dir="$etc/${dir#./}"
    suffix=$(basename "$import")
    suffix=${suffix#*\*}
    file="$dir/$1.w4os${suffix:-.caddyfile}"
    mkdir -p "$dir"
    printf '%s\n' "$2" >"$file"
    said=$(caddy validate --config "$etc/Caddyfile" --adapter caddyfile 2>&1) || {
        rm -f "$file"
        die "Caddy refuses the configuration, the site is not installed: $said"
    }
    if [ -d /run/systemd/system ] || [ -n "${W4OS_SITE_SYSTEMD:-}" ]; then
        said=$(systemctl reload caddy 2>&1) || die "the site is in $file, but Caddy did not reload ($said)"
    else
        # Without systemd (a container): the Caddy that runs told to read its config again
        said=$(caddy reload --config "$etc/Caddyfile" --adapter caddyfile 2>&1) || die "the site is in $file, but Caddy did not reload ($said)"
    fi
    success "the site is in $file, Caddy reloaded"
}

# apache_blocks HOST SCHEME: the blocks of the sites of Apache that serve HOST (its ServerName or a ServerAlias), one a line,
# "file<TAB>first line<TAB>last line": the ones of SCHEME (https: its port 443 or SSLEngine on), and the http ones that do more than
# redirect to https, as their file has them (the real file of a link of sites-enabled)
apache_blocks() {
    local host=$1 scheme=$2 etc=${W4OS_SITE_APACHE_ETC:-/etc/apache2} link file
    for link in "$etc"/sites-enabled/*.conf; do
        [ -e "$link" ] || continue
        file=$(readlink -f -- "$link")
        awk -v host="$(tr '[:upper:]' '[:lower:]' <<<"$host")" -v scheme="$scheme" -v file="$file" '
            function done_block() {
                if (!named) return
                tls = (port == "443" || ssl)
                if (scheme == "https" && (tls || !redirects)) print file "\t" first "\t" NR
                else if (scheme == "http" && !tls) print file "\t" first "\t" NR
            }
            /^[[:space:]]*<VirtualHost[[:space:]>]/ { inside = 1; first = NR; named = 0; ssl = 0; redirects = 0; port = ""
                if (match($0, /:[0-9]+/)) port = substr($0, RSTART + 1, RLENGTH - 1); next }
            inside && /^[[:space:]]*<\/VirtualHost>/ { done_block(); inside = 0; next }
            inside && tolower($1) ~ /^(servername|serveralias)$/ { for (i = 2; i <= NF; i++) if (tolower($i) == host) named = 1 }
            inside && tolower($1) == "sslengine" && tolower($2) == "on" { ssl = 1 }
            inside && tolower($1) ~ /^redirect(match|permanent)?$/ && $0 ~ /https:/ { redirects = 1 }
            inside && tolower($1) == "rewriterule" && $3 ~ /^https:/ && $0 ~ /R=|R,|\[R\]/ { redirects = 1 }
        ' "$file"
    done | sort -u
}

# The two lines a block of a site of the host is given, and the marker that finds them again
APACHE_MARK='# w4os-site: the site under its path (w4os-site web apache --remove takes it out)'

# The modules of Apache the site needs (PHP-FPM through proxy_fcgi, which needs proxy)
APACHE_MODULES='rewrite proxy proxy_fcgi alias'

# apache_off_modules ETC: the modules the site needs that Apache has not enabled, one a line
apache_off_modules() {
    local module
    for module in $APACHE_MODULES; do
        [ -e "$1/mods-enabled/$module.load" ] || printf '%s\n' "$module"
    done
}

# apache_prefixed HOST PREFIX SOCKET MODE SCHEME: the site under PREFIX on HOST alone, never on another site of Apache: a file of
# its own (/etc/apache2/w4os/HOST.conf: the helpers of the grid of this machine, the site, its PHP), included by one line in each
# block that serves HOST (an Apache site cannot be given a path from outside its own file), IncludeOptional so that Apache starts
# without the file; a copy of each file before it is changed. MODE: print, vhosts (the files that would be changed), install, remove
apache_prefixed() {
    local host=$1 prefix=/${2#/} socket=$3 mode=$4 scheme=$5 etc=${W4OS_SITE_APACHE_ETC:-/etc/apache2} grid helpers= handler= text said
    prefix=${prefix%/}
    [[ $host != *://* ]] || { scheme=${host%%://*}; host=${host#*://}; }
    local own="$etc/w4os/$host.conf" blocks files file ends
    blocks=$(apache_blocks "$host" "$scheme")
    files=$(cut -f1 <<<"$blocks" | sed '/^$/d' | sort -u)
    case $mode in
    vhosts)
        printf '%s\n' "$files" | sed '/^$/d'
        return
        ;;
    modules)
        apache_off_modules "$etc"
        return
        ;;
    remove)
        require apache2ctl
        for file in $(grep -l -F -- "$APACHE_MARK" "$etc"/sites-available/*.conf 2>/dev/null); do
            apache_unmark "$file"
        done
        rm -f "$own"
        # The modules it enabled itself disabled again, the last ones first (proxy_fcgi before proxy); the others as they were
        if [ -f "$own.modules" ]; then
            said=$(a2dismod -q $(tac "$own.modules") 2>&1) || die "Apache's modules could not be disabled again: $said"
            rm -f "$own.modules"
        fi
        said=$(apache2ctl configtest 2>&1) || die "Apache refuses its configuration once the site is taken out: $said"
        apache_reload
        success "the site is out of Apache ($host)"
        return
        ;;
    esac
    [ -z "$socket" ] || handler=$(printf '\t<FilesMatch "\\.php$">\n\t\tSetHandler "proxy:unix:%s|fcgi://localhost"\n\t</FilesMatch>' "$socket")
    grid=$(yaml_get "$CONFIG/plugins/w4os.yaml" grid)
    if [ -n "$grid" ] && command -v "${W4OS_SITE_OPENSIM:-opensim}" >/dev/null 2>&1; then
        helpers=$("${W4OS_SITE_OPENSIM:-opensim}" web "$grid" snippet apache 2>/dev/null | sed -e '/^[[:space:]]*#/d' -e '/^[[:space:]]*$/d' || true)
        grep -q '^AliasMatch ' <<<"$helpers" || helpers=
        # The handler as it is (awk -v would read its backslashes as escapes); none where the helpers have their own pool already
        [ -z "$helpers" ] || helpers=$(printf '# Helpers of the grid %s\n%s\n' "$grid" "$(W4OS_HANDLER=$(grep -q 'SetHandler' <<<"$helpers" || printf '%s' "$handler") awk '/^<\/Directory>/ && ENVIRON["W4OS_HANDLER"] != "" { print ENVIRON["W4OS_HANDLER"] } { print }' <<<"$helpers")")
    fi
    text=$(
        printf '# The w4os site under %s on %s alone, included by its sites (w4os-site web apache --prefix %s)\n' "$prefix" "$host" "$prefix"
        [ -z "$helpers" ] || printf '%s\n' "$helpers"
        printf '# Website\nRedirectMatch 308 ^%s$ %s/\nAlias %s %s\n<Directory %s>\n\tRequire all granted\n\tAllowOverride All\n\tOptions -Indexes +FollowSymLinks -MultiViews\n' "$prefix" "$prefix" "$prefix" "$ROOT" "$ROOT"
        [ -z "$handler" ] || printf '%s\n' "$handler"
        printf '</Directory>\n'
    )
    if [ "$mode" != install ]; then
        printf '%s\n' "$text"
        return
    fi
    require apache2ctl
    [ -n "$files" ] || die "no site of Apache serves $host: the website is put in one of its sites"
    [ -n "$socket" ] || apache2ctl -M 2>/dev/null | grep -q php ||
        die "no PHP for Apache: no pool of PHP-FPM (/etc/php/<version>/fpm/pool.d) and no PHP module of Apache: apt install php-fpm, then this command again"
    mkdir -p "$etc/w4os" && printf '%s\n' "$text" >"$own" || die "cannot write $own"
    # The global conf of before, for every site of Apache: never again
    [ ! -e "$etc/conf-available/w4os-site.conf" ] || { a2disconf -q w4os-site >/dev/null 2>&1 || true; rm -f "$etc/conf-available/w4os-site.conf"; }
    # The line before the end of each block, the last ones first (the numbers of the others stay right); a copy of each file once
    for file in $files; do
        [ -e "$file.before-w4os" ] || cp -p -- "$file" "$file.before-w4os" || die "cannot keep a copy of $file"
        # Each block that has not the line yet gets it before its end
        ends=$(awk -F'\t' -v f="$file" '$1 == f { print $2 ":" $3 }' <<<"$blocks" | tr '\n' ' ')
        text=$(awk -v ends="$ends" -v m="$APACHE_MARK" -v inc="IncludeOptional $own" '
            BEGIN { n = split(ends, list, " "); for (i = 1; i <= n; i++) { split(list[i], b, ":"); last[b[2]] = b[1] } }
            index($0, m) { marked[NR] = 1 }
            { lines[NR] = $0 }
            END {
                for (i = 1; i <= NR; i++) {
                    if (i in last) {
                        has = 0
                        for (j = last[i]; j < i; j++) if (j in marked) has = 1
                        if (!has) { print "    " m; print "    " inc }
                    }
                    print lines[i]
                }
            }' "$file") && printf '%s\n' "$text" >"$file" || die "cannot write $file"
    done
    # The modules it enables itself kept, to be disabled again by --remove (never the ones Apache had)
    local off
    off=$(apache_off_modules "$etc")
    said=$(a2enmod -q $APACHE_MODULES 2>&1) || die "Apache's modules could not be enabled: $said"
    said=$(apache2ctl configtest 2>&1) || {
        for file in $files; do apache_unmark "$file"; done
        rm -f "$own"
        [ -z "$off" ] || a2dismod -q $(tac <<<"$off") >/dev/null 2>&1 || true
        die "Apache refuses the configuration, nothing is changed: $said"
    }
    [ -z "$off" ] || printf '%s\n' "$off" >>"$own.modules"
    # Grav's rules under an alias: their base is the prefix
    [ ! -f "$ROOT/.htaccess" ] || sed -i -E "s|^#? ?RewriteBase .*|RewriteBase $prefix|" "$ROOT/.htaccess"
    yaml_set "$CONFIG/system.yaml" custom_base_url "$scheme://$host$prefix"
    owner
    chown "$OWNER:$GROUP" "$CONFIG/system.yaml" "$ROOT/.htaccess" 2>/dev/null || true
    rm -rf "${W4OS_SITE_CACHE:-$ROOT/cache}"/* 2>/dev/null || true
    apache_reload
    success "the site is in $own, included by $(tr '\n' ' ' <<<"$files" | sed 's/ $//; s/ /, /g'), Apache reloaded"
}

# apache_unmark FILE: the two lines of the site taken out of a file of a site of Apache (the marker and the line after it)
apache_unmark() {
    local text
    text=$(awk -v m="$APACHE_MARK" 'skip { skip = 0; next } index($0, m) { skip = 1; next } { print }' "$1") && printf '%s\n' "$text" >"$1"
}

# Apache told to read its configuration again: by systemd, else the Apache that runs (a container)
apache_reload() {
    local said
    if [ -d /run/systemd/system ] || [ -n "${W4OS_SITE_SYSTEMD:-}" ]; then
        said=$(systemctl reload apache2 2>&1) || die "Apache did not reload ($said)"
    else
        # An Apache it starts is never on the terminal (it would keep it open after the run)
        said=$(apache2ctl graceful 2>&1 </dev/null) || die "Apache did not reload ($said)"
    fi
}

web() {
    local server=${1:-} host= port= install= prefix=
    shift || true
    while [ $# -gt 0 ]; do
        case $1 in
        --host) host=$2; shift 2 ;;
        --port) port=$2; shift 2 ;;
        --prefix) prefix=$2; shift 2 ;;
        --install) install=1; shift ;;
        --vhosts) install=vhosts; shift ;;
        --modules) install=modules; shift ;;
        --remove) install=remove; shift ;;
        *) die "unknown option $1" ;;
        esac
    done
    # The host and the port of the address of the site (custom_base_url) when not given, never the name of the machine
    local url scheme=
    url=$(yaml_get "$CONFIG/system.yaml" custom_base_url)
    if [ -z "$host" ]; then
        [[ $url != *://* ]] || scheme=${url%%://*}
    fi
    url=${url#*://}
    url=${url%%/*}
    if [ -z "$host" ]; then
        host=${url%%:*}
        [ -n "$port" ] || [ "$url" = "${url#*:}" ] || port=${url#*:}
    fi
    host=${host:-localhost}
    local socket
    socket=${W4OS_SITE_PHP_SOCKET:-$(php_socket)}
    case $server in
    apache)
        [ -n "${W4OS_SITE_PHP_SOCKET:-}" ] || socket=$(apache_socket "$socket")
        if [ -n "$prefix" ]; then
            local mode=print
            [ -z "$install" ] || mode=$install
            [ "$mode" != 1 ] || mode=install
            apache_prefixed "$host" "$prefix" "$socket" "$mode" "${scheme:-https}"
            return
        fi
        port=${port:-80}
        local listen= php= conf
        [ "$port" = 80 ] || [ "$port" = 443 ] || listen="Listen $port"
        [ -z "$socket" ] || php=$(printf '<FilesMatch "\\.php$">\n        SetHandler "proxy:unix:%s|fcgi://localhost"\n    </FilesMatch>' "$socket")
        conf=$(<"$SHARE/web/apache.conf")
        conf=${conf//\{\{root\}\}/$ROOT}
        conf=${conf//\{\{host\}\}/$host}
        conf=${conf//\{\{port\}\}/$port}
        conf=${conf//\{\{listen\}\}/$listen}
        conf=${conf//\{\{php\}\}/$php}
        if [ -z "$install" ]; then
            printf '%s\n' "$conf"
            return
        fi
        require a2ensite apache2ctl
        # Never a site whose PHP Apache would show as text: PHP-FPM (its pool) or Apache's own PHP module
        [ -n "$socket" ] || apache2ctl -M 2>/dev/null | grep -q php ||
            die "no PHP for Apache: no pool of PHP-FPM (/etc/php/<version>/fpm/pool.d) and no PHP module of Apache: apt install php-fpm, then this command again"
        printf '%s\n' "$conf" >/etc/apache2/sites-available/w4os-site.conf
        local said
        said=$(a2enmod -q rewrite proxy_fcgi 2>&1 && a2ensite -q w4os-site 2>&1) ||
            die "Apache's modules or the site could not be enabled: $said"
        said=$(apache2ctl configtest 2>&1) || {
            a2dissite -q w4os-site >/dev/null 2>&1 || true
            die "Apache refuses the configuration, the site is not enabled (/etc/apache2/sites-available/w4os-site.conf): $said"
        }
        # The address of the site in what it writes (the links of its mails, the pictures), whatever address it is visited at
        local base="http://$host"
        [ "$port" = 80 ] || base="$base:$port"
        yaml_set "$CONFIG/system.yaml" custom_base_url "$base"
        owner
        chown "$OWNER:$GROUP" "$CONFIG/system.yaml" 2>/dev/null || true
        rm -rf "${W4OS_SITE_CACHE:-$ROOT/cache}"/* 2>/dev/null || true
        # Apache takes the site at its reload: it runs, or it is started, never left unsaid
        said=$(systemctl reload apache2 2>&1) || {
            local pid=/run/apache2/apache2.pid
            [ -s "$pid" ] && kill -0 "$(cat "$pid")" 2>/dev/null &&
                die "the site is enabled, but Apache did not reload ($said): reload it (systemctl reload apache2, or apache2ctl graceful without systemd), then this command again"
            die "the site is enabled, but Apache isn't running ($said): start it (systemctl start apache2, or apache2ctl start without systemd), then this command again"
        }
        check_site "$base" "$port" "$host" "$socket"
        ;;
    caddy)
        [ -n "$socket" ] || die "Caddy needs PHP-FPM"
        # Its addresses (the hosts given, separated by commas), http:// when the address of the site says so, else Caddy's https
        local tab=$'\t' addresses= address name names
        IFS=, read -ra names <<<"$host"
        for name in "${!names[@]}"; do
            # A host given with its scheme: the scheme is the address's, the name is the host alone (the name of the file)
            [[ ${names[$name]} != http://* ]] || scheme=http
            names[$name]=${names[$name]#*://}
        done
        for name in "${names[@]}"; do
            address=$name${port:+:$port}
            [ "$scheme" != http ] || address="http://$address"
            addresses+=${addresses:+, }$address
        done
        prefix=/${prefix#/}
        prefix=${prefix%/}
        local text
        if [ -z "$prefix" ]; then
            # A site block of its own (Grav's Caddyfile, made for a site alone, in braces), for the Caddyfile of the machine to
            # import next to its other sites
            text=$(printf '# The w4os site (w4os-site web caddy)\n%s {\n%sencode gzip\n%simport %s %s unix/%s /index.php\n}\n' \
                "$addresses" "$tab" "$tab" "$(grav_snippet)" "$ROOT" "$socket")
        else
            text=$(caddy_prefixed "$addresses" "$prefix" "$socket")
        fi
        if [ -z "$install" ]; then
            printf '%s\n' "$text"
            return
        fi
        caddy_install "${names[0]}" "$text"
        ;;
    nginx)
        sed "s|root /home/USER/www/html;|root $ROOT;|; s|server_name localhost;|server_name $host;|; s|listen 80;|listen ${port:-80};|; s|unix:/var/run/php/php-fpm.sock|unix:${socket:-/run/php/php-fpm.sock}|" "$ROOT/webserver-configs/nginx.conf"
        ;;
    *) die "w4os-site web apache|caddy|nginx [--host <name>] [--port <port>] [--install]" ;;
    esac
}

# The version of the site: the package that installed it, else its git version in a clone, else the one being worked on
if [[ " $* " == *" --version "* || " $* " == *" -V "* ]]; then
    here=$(cd "$(dirname "$(realpath "$0")")/.." && pwd)
    version=
    if [[ "$here" == /usr/share/w4os-site* ]]; then
        version=$(dpkg-query -W -f='${Version}' w4os-site 2>/dev/null) || version=
    fi
    [[ -n "$version" || ! -e "$here/.git" ]] || version=$(git -C "$here" describe --tags --always --dirty 2>/dev/null) || version=
    [[ -n "$version" || ! -f "$here/.version" ]] || version="$(<"$here/.version") (development)"
    echo "w4os-site ${version:-unknown}"
    exit 0
fi

case ${COMMAND:-} in
setup | status | web)
    # Older bash-tools keep the command in the arguments
    [ "${1:-}" != "$COMMAND" ] || shift
    $COMMAND "$@"
    ;;
*)
    sed -n '3,12p' "$0" | sed 's/^# \{0,1\}//'
    exit 1
    ;;
esac
