#!/usr/bin/env bash
# opensim web: show, check, or print web-server snippets for a grid.

USAGE='opensim web [GRID] [show|check]
       opensim web [GRID] snippet caddy|nginx|apache [--prefix /PATH] [--docroot DIR]
       opensim web [GRID] paths --outside /PATH
       opensim web [GRID] api caddy|nginx|apache [--install] [--socket PATH] [--port N] [--web-group GROUP] [--docroot DIR]
       opensim web [GRID] site --install [--address URL] [--edit-vhosts]
       opensim web [GRID] site --vhosts
       opensim web [GRID] set PAGE URL
       GRID: the nick of a grid or its name'
HELP="Show grid web services and who serves each page (the helpers under their base, the site elsewhere), check their URLs, print a server snippet, or set the address of a page (helpers, search, profile, guide, welcome, status, directory). api prints what serves the engine API to the sites of this machine as the user of the instances: a PHP-FPM pool of its own, and a listener on 127.0.0.1 for its paths only (the site then uses engine remote with a key); api caddy --install writes both (the pool in PHP-FPM, the listener in the sites Caddy imports) and reloads them; site --install puts the Quick Start website of the grid at the address its setup chose (--address another one, kept alone: no other address of the grid follows it) (the engine API, the site connected to it, its file beside the site of the host; for Apache, one line in each site serving the host, asked, or --edit-vhosts); site --vhosts names those files. Options: --docroot DIR, --socket PATH, --port N, --web-group GROUP."

source "$(dirname "$(realpath "${BASH_SOURCE[0]}" 2>/dev/null || echo "${BASH_SOURCE[0]}")")/../src/lib/common"

# The pools of the suite (the engine API, the helpers) and the listener of the engine API in place: the pools in PHP-FPM, the listener in the folder of sites the Caddyfile
# imports (never the Caddyfile itself), checked by Caddy (taken back when refused), then both reloaded
install_api() { # grid, then the options of web (api caddy|apache)
	local grid=$1 server text etc=${OPENSIM_CADDY_ETC:-/etc/caddy} apache=${OPENSIM_APACHE_ETC:-/etc/apache2} php=${OPENSIM_PHP_ETC:-/etc/php}
	local pools import dir suffix file said version user api code arg previous= group= written
	for arg in "$@"; do
		[[ "$previous" != api ]] || server=$arg
		[[ "$previous" != --web-group ]] || group=$arg
		previous=$arg
	done
	# What to write, as the account of the instances (the port of the API is kept in the conf of the grid, which is theirs)
	user=$(install_accounts | sed -n 's/^SystemUser=//p' | head -n 1)
	if [[ $(id -u) -eq 0 && -n "$user" && "$user" != root ]]; then
		text=$(runuser -u "$user" -- "$0" "$@") || exit
	else
		text=$(run web "$@") || exit
	fi
	pools=$(ls -d "$php"/*/fpm/pool.d 2>/dev/null | sort -V | tail -n 1)
	[[ -n "$pools" ]] || die "No PHP-FPM on this machine."$'\n'"sudo apt install php-fpm"
	version=$(basename "$(dirname "$(dirname "$pools")")")
	case $server in
	caddy)
		import=$(sed -n 's/^[[:space:]]*import[[:space:]]\{1,\}\([^[:space:]]*\*[^[:space:]]*\).*/\1/p' "$etc/Caddyfile" 2>/dev/null | head -n 1)
		[[ -n "$import" ]] || die "$etc/Caddyfile imports no folder of sites."$'\n'"Add this line to it:"$'\n'"import sites/*"
		dir=$(dirname "$import")
		[[ "$dir" == /* ]] || dir="$etc/${dir#./}"
		suffix=$(basename "$import")
		suffix=${suffix#*\*}
		file="$dir/$grid-api.w4os${suffix:-.caddyfile}"
		;;
	apache)
		dir=$apache/conf-available
		file="$dir/w4os-api-$grid.conf"
		;;
	*) die "the engine API is installed for caddy or apache" ;;
	esac
	mkdir -p "$dir" || die "Cannot write in $dir."$'\n'"${OPENSIM_AGAIN:+sudo $OPENSIM_AGAIN}"
	# The pools of the suite, the API's and the helpers', written by the engine; their sockets for the group of the web server
	written=$(W4OS_PHP_ETC=$php php "$(dirname "$OPENSIM_API")/opensim-pools.php" --web-group "${group:-$(web_group "$server")}") ||
		die "Cannot write the pools of PHP-FPM in $pools."$'\n'"${OPENSIM_AGAIN:+sudo $OPENSIM_AGAIN}"
	{
		echo "# The engine API of the grid $grid, for the sites of this machine only (opensim web $grid api $server --install)"
		if [[ "$server" == caddy ]]; then
			sed -n '/^http:\/\/127\.0\.0\.1:/,/^}$/p' <<<"$text"
		else
			sed -n '/^Listen 127\.0\.0\.1:/,/^<\/VirtualHost>$/p' <<<"$text"
		fi
	} >"$file" || die "Cannot write $file."$'\n'"${OPENSIM_AGAIN:+sudo $OPENSIM_AGAIN}"
	if [[ "$server" == caddy ]]; then
		said=$(caddy validate --config "$etc/Caddyfile" --adapter caddyfile 2>&1) || { rm -f "$file"; die "Caddy refuses the listener of the engine API: $said"; }
		api="$(sed -n 's/^\(http:\/\/127\.0\.0\.1:[0-9]*\) {$/\1/p' "$file")/api"
	else
		said=$({ a2enmod -q proxy_fcgi alias && a2enconf -q "w4os-api-$grid" && apache2ctl configtest; } 2>&1) || {
			a2disconf -q "w4os-api-$grid" >/dev/null 2>&1
			rm -f "$file"
			die "Apache refuses the listener of the engine API: $said"
		}
		api="http://$(sed -n 's/^Listen \(127\.0\.0\.1:[0-9]*\)$/\1/p' "$file")/api"
	fi
	if [[ -d /run/systemd/system || -n "${OPENSIM_SYSTEMD:-}" ]]; then
		# A pool written anew is restarted: a reload keeps the sockets PHP-FPM has open, with their owner and group of before
		if [[ -n "$written" ]]; then systemctl restart "php$version-fpm"; else systemctl reload "php$version-fpm" || systemctl restart "php$version-fpm"; fi ||
			die "php$version-fpm did not take the pools in $pools"
		if [[ "$server" == caddy ]]; then systemctl reload caddy; else systemctl reload apache2; fi || die "the web server did not reload with $file"
	else
		# Without systemd (a container): the running ones told to read their config again
		pkill -USR2 -f "php-fpm: master process" || die "PHP-FPM does not run. Its pools are in $pools."$'\n'"Start php-fpm$version"
		if [[ "$server" == caddy ]]; then
			caddy reload --config "$etc/Caddyfile" --adapter caddyfile >/dev/null 2>&1
		else
			apache2ctl graceful </dev/null >/dev/null 2>&1
		fi || die "the web server did not reload with $file"
	fi
	# Answered, a key asked (401) or given: the pool and the listener are there; nothing, or 502, is no API
	for _ in 1 2 3 4 5; do
		code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 10 "$api/info" 2>/dev/null) || code=000
		[[ "$code" == 000 || "$code" == 502 || "$code" == 503 ]] || break
		sleep 1
	done
	[[ "$code" != 000 && "$code" != 502 && "$code" != 503 ]] || die "The engine API does not answer at $api: HTTP $code."$'\n'"See the log of php$version-fpm"
	say "✓ Engine API: $api"
}

# The group the web server runs as, the one that reaches the sockets of the pools: Apache's of its envvars, caddy for Caddy
web_group() { # server
	local group=
	if [[ "$1" == apache ]]; then
		group=$(sed -nE 's/^[[:space:]]*export[[:space:]]+APACHE_RUN_GROUP=["\x27]?([^"\x27[:space:]]+).*/\1/p' "${OPENSIM_APACHE_ETC:-/etc/apache2}/envvars" 2>/dev/null | tail -n 1)
		[[ "$group" != *'$'* ]] || group=
	fi
	[[ -n "$group" ]] || group=$([[ "$1" == caddy ]] && echo caddy || echo www-data)
	echo "$group"
}

# The web server the sites of this machine are served by: Caddy, else Apache (the one that runs, its config there)
web_server() {
	if command -v caddy >/dev/null 2>&1 && [[ -f "${OPENSIM_CADDY_ETC:-/etc/caddy}/Caddyfile" ]]; then
		echo caddy
	elif command -v apache2ctl >/dev/null 2>&1 && [[ -d "${OPENSIM_APACHE_ETC:-/etc/apache2}/conf-available" ]]; then
		echo apache
	else
		return 1
	fi
}

# Where the website (w4os-site) is on this machine and where it comes from, as the engine finds it: its package, else its clone beside
# this one, built
site_found() {
	[[ -n "${_site_share+set}" ]] || IFS=$'\t' read -r _site_share _site_source < <(run component site 2>/dev/null) || true
	_site_share=${_site_share:-}
	[[ -n "$_site_share" ]] || command -v w4os-site >/dev/null 2>&1
}

# The command of the website: the one of its package, else the one of its clone, told where its files and this command line are
site() {
	site_found || return 1
	if [[ -n "$_site_share" && "${_site_source:-}" != package ]]; then
		PATH="$CLI_ROOT/vendor/magicoli/bash-tools/bin:$PATH" W4OS_SITE_SHARE=$_site_share W4OS_SITE_OPENSIM="$CLI_ROOT/bin/opensim" "$_site_share/bin/w4os-site" "$@"
	else
		w4os-site "$@"
	fi
}

# The site made from the files of a clone, or brought up to them: what the package of the website does when it is installed
site_tree() {
	site_found && [[ -n "$_site_share" && "${_site_source:-}" != package ]] || return 0
	[[ -d /var/lib/w4os ]] || install -d -m 755 /var/lib/w4os
	W4OS_SITE_SEED="$_site_share/grav" W4OS_SITE_LEGACY="$_site_share/grav17" W4OS_SITE_PAGES_HISTORY="$_site_share/pages-history" \
		"$_site_share/bin/w4os-site-tree" configure
}

# The Quick Start website of a grid in place, at the address the grid keeps (site of the API): the engine API for the sites of this
# machine, the site connected to it, its file beside the site of the host (never the host's own file)
install_site() { # grid [edit: the files of the sites of Apache may be given their line]
	local grid=$1 edit=${2:-} detail address host prefix api helpers name server files
	detail=$(engine GET "/grids/$grid" 2>/dev/null) || die "there is no grid $grid here"
	address=$(jq -r '.data.attributes.site // empty' <<<"$detail")
	name=$(jq -r '.data.attributes.name // empty' <<<"$detail")
	[[ -n "$address" ]] || die "$grid has no Quick Start website: its setup did not choose one."$'\n'"opensim web $grid site --install --address URL"
	site_found || die "w4os-site is not installed."$'\n'"sudo apt install w4os-site"
	server=$(web_server) || die "no Caddy nor Apache on this machine: the Quick Start website is put beside a site of one of them"
	host=$(sed -E 's#^([a-z]+://[^/:]+).*#\1#' <<<"$address")
	prefix=$(sed -E 's#^[a-z]+://[^/]+##; s#/$##' <<<"$address")
	# Apache, a website under a path of its own: one line in each site that serves the host, never without its yes. At the root
	# of a host the command of the website installs its own site, nothing of the host is changed
	if [[ "$server" == apache && -n "$prefix" ]]; then
		files=$(site web apache --host "$host" --prefix "$prefix" --vhosts 2>/dev/null | paste -sd, - | sed 's/,/, /g')
		[[ -n "$files" ]] || die "no site of Apache serves ${host#*://}: the website is put in one of its sites"
		# The modules of Apache it enables, said with the line: a change of the host
		local modules
		modules=$(site web apache --host "$host" --prefix "$prefix" --modules 2>/dev/null | paste -sd, - | sed 's/,/, /g')
		if [[ -z "$edit" ]]; then
			[[ -t 0 ]] || die "The website needs one line in $files${modules:+ and the modules $modules of Apache}."$'\n'"${OPENSIM_AGAIN:-opensim web $grid site --install} --edit-vhosts"
			read -r -p "Add one line to $files${modules:+ and enable the modules $modules of Apache}? [Y/n] " edit
			[[ -z "$edit" || "$edit" == [yY]* ]] || die "the website is not installed: it needs that line"
		fi
	fi
	install_api "$grid" api "$server" || exit
	api=$(run web "$grid" api "$server" | sed -n 's/.*api_url \(http:\/\/127\.0\.0\.1:[0-9]*\/api\).*/\1/p' | head -n 1)
	helpers=$(run web "$grid" show | sed -n 's/^Helpers:[[:space:]]*//p' | head -n 1)
	site_tree >/dev/null || die "the site could not be made from $_site_share"
	site setup --grid "$grid" --api "$api" --url "$helpers" --title "$name" </dev/null || die "the site could not be connected to $grid"
	site web "$server" --host "$host" ${prefix:+--prefix "$prefix"} --install || die "the site could not be put in $server"
	say "✓ Website: $address"
}

# The files of the sites of Apache the website of a grid would be included by, one a line (for the question), nothing for Caddy
site_vhosts() { # grid
	local address
	address=$(engine GET "/grids/$1" 2>/dev/null | jq -r '.data.attributes.site // empty')
	[[ -n "$address" && "$(web_server)" == apache ]] || return 0
	# For a website under a path of its own only (see install_site)
	local prefix
	prefix=$(sed -E 's#^[a-z]+://[^/]+##; s#/$##' <<<"$address")
	[[ -n "$prefix" ]] || return 0
	site web apache --host "$(sed -E 's#^([a-z]+://[^/:]+).*#\1#' <<<"$address")" --prefix "$prefix" --vhosts
}

if [[ "${2:-}" == site && " $* " == *" --install "* ]]; then
	# Another address for the website: its own setting, kept before it is installed there
	address=
	for ((i = 1; i <= $#; i++)); do
		[[ "${!i}" == --address ]] && { j=$((i + 1)); address=${!j:-}; [[ -n "$address" ]] || die "--address requires a URL"; }
		[[ "${!i}" == --address=* ]] && address=${!i#--address=}
	done
	if [[ -n "$address" ]]; then
		reply=$(engine POST "/grids/$(jq -rn --arg v "$1" '$v | @uri')/address" --data=- <<<"$(jq -cn --arg w "$address" '{data: {type: "address", attributes: {website: $w, mode: "apply"}}}')") || true
		why=$(jq -er 'select(.status? >= 400) | .detail // .title' <<<"$reply" 2>/dev/null) && die "$why"
	fi
	install_site "$1" "$([[ " $* " != *" --edit-vhosts "* ]] || echo yes)"
	exit
fi
if [[ "${2:-}" == site && " $* " == *" --vhosts "* ]]; then
	site_vhosts "$1"
	exit
fi

# api alone: for Caddy, the web server the sites of the kit are put beside
args=()
for arg in "$@"; do
	# An option right after api: no web server named
	[[ ${#args[@]} -gt 0 && "${args[-1]}" == api && "$arg" == -* ]] && args+=(caddy)
	args+=("$arg")
done
[[ ${#args[@]} -eq 0 || "${args[-1]}" != api ]] || args+=(caddy)
set -- "${args[@]}"

if [[ " $* " == *" --install "* && ( " $* " == *" api caddy "* || " $* " == *" api apache "* ) ]]; then
	args=()
	for arg in "$@"; do [[ "$arg" == --install ]] || args+=("$arg"); done
	install_api "${args[@]}"
	exit
fi
run web "$@"
