#!/usr/bin/env bash
# What: makes ONE website of ONE CWP hosting account serve its document root (agent op ensure-website).
#       The hostname must be the account's own CWP domain or a subdomain of it. The docroot directory is created owned by
#       the account (group nobody, setgid, so Apache can read static files). With a php version the account gets a
#       php-fpm pool for it and the vhost a marked handler block; with link_root the pool also gets the lines a
#       symlink switch behind Apache needs. A vhost CWP made (the main domain) is kept as it is and only
#       gets the handler; a vhost for any other hostname is written by this helper, marked as its own.
#       Idempotent. Every edited file is copied first; both configurations are tested before a graceful reload and
#       everything is restored when a test fails.
# Usage (root, called by hostpanel-ssh-key-agent): ensure-website <account> <hostname> <docroot> <php|""> <link_root 0|1>
# Exit: 0 done, 2 bad arguments, 3 not the account's (hostname, vhost or docroot), 4 conflict (vhost serves another
#       document root; with link_root, anything at the link point that is not a symlink), 5 php version not installed,
#       other = failed. Prints one `RESULT {"changed":true|false[,"php_cli":"/abs/php"]}` line; php_cli is there when a
#       php version was asked for.
set -euo pipefail
HELPER_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=hp-common.sh
. "$HELPER_DIR/hp-common.sh"

[ $# -eq 5 ] || hp_die "$EXIT_BAD_ARGS" "usage: ensure-website <account> <hostname> <docroot> <php or empty> <link_root 0|1>"
HOSTN="$2"; DOCROOT="$3"; PHP="$4"; LINK="$5"
hp_require_account "$1"
[[ "$HOSTN" =~ $HOSTNAME_RE ]] || hp_die "$EXIT_BAD_ARGS" "bad hostname"
[[ "$DOCROOT" =~ $DOCROOT_RE ]] && [[ "$DOCROOT" != *..* ]] || hp_die "$EXIT_BAD_ARGS" "bad docroot"
[ -z "$PHP" ] || [[ "$PHP" =~ $PHP_RE ]] || hp_die "$EXIT_BAD_ARGS" "bad php version"
[[ "$LINK" =~ ^[01]$ ]] || hp_die "$EXIT_BAD_ARGS" "bad link_root"
[ "$LINK" = 0 ] || [ -n "$PHP" ] || hp_die "$EXIT_BAD_ARGS" "link_root needs a php version"

# The hostname is the account's CWP domain or a subdomain of it, never anything else.
DOMAIN="$(hp_mysql -e "SELECT domain FROM root_cwp.user WHERE username='$ACCOUNT'" </dev/null)" || hp_die 1 "cwp lookup failed"
[[ "$DOMAIN" =~ $HOSTNAME_RE ]] || hp_die "$EXIT_NOT_OWNED" "no domain for $ACCOUNT"
{ [ "$HOSTN" = "$DOMAIN" ] || [[ "$HOSTN" == *".$DOMAIN" ]]; } || hp_die "$EXIT_NOT_OWNED" "$HOSTN is not a domain of $ACCOUNT"

# The document root resolves inside the home and never into .ssh or .conf (a symlink cannot lead out either).
HOME_REAL="$(realpath -- "$HOME_DIR")"
TARGET="$(realpath -m -- "$HOME_DIR/$DOCROOT")"
hp_docroot_allowed "$TARGET" || hp_die "$EXIT_BAD_ARGS" "docroot not allowed"
DOCROOT_L="$HOME_L/$DOCROOT"

# With link_root the last component is the link point: the deployer makes it as a symlink, so it is never created here
# and the directories to create are those of its parent. Anything at the link point that is not a symlink (a directory
# of the account's own, a file) is a conflict and is never removed.
CREATE_BASE="$TARGET"
if [ "$LINK" = 1 ]; then
  CREATE_BASE="$(realpath -m -- "$HOME_DIR/$(dirname -- "$DOCROOT")")"
  [ "$CREATE_BASE" = "$HOME_REAL" ] || hp_docroot_allowed "$CREATE_BASE" || hp_die "$EXIT_BAD_ARGS" "docroot not allowed"
  if { [ -e "$HOME_DIR/$DOCROOT" ] || [ -L "$HOME_DIR/$DOCROOT" ]; } && [ ! -L "$HOME_DIR/$DOCROOT" ]; then
    hp_die "$EXIT_CONFLICT" "$DOCROOT exists and is not a symlink"
  fi
fi

NN=""; FPM_L=""; FPM=""; POOL=""; SOCK=""; PHP_CLI=""
if [ -n "$PHP" ]; then
  NN="${PHP/./}"
  FPM_L="$FPM_PREFIX$NN"
  FPM="$ROOT$FPM_L"
  PHP_CLI="$(hp_php_cli "$PHP")"
  [ -n "$PHP_CLI" ] || hp_die "$EXIT_PHP_UNSUPPORTED" "php $PHP is not installed"
  POOL="$FPM/usr/etc/php-fpm.d/users/$ACCOUNT.conf"
  SOCK="$FPM_L/usr/var/sockets/$ACCOUNT.sock"
fi

# Refuse before changing anything: every vhost for this hostname must be the account's and serve this docroot.
for f in $(hp_vhost_files "$HOSTN"); do
  owner="$(hp_vhost_account "$f")"
  [ "$owner" = "$ACCOUNT" ] || hp_die "$EXIT_NOT_OWNED" "$(basename "$f") belongs to another account"
  hp_is_managed "$f" || [ "$(hp_vhost_docroot "$f")" = "$DOCROOT_L" ] \
    || hp_die "$EXIT_CONFLICT" "$(basename "$f") serves another document root"
done

hp_guard
CHANGED=0; VHOST_CHANGED=0; POOL_CHANGED=0

# 1. Document root: missing directories are created owned by the account, group nobody, setgid. With link_root the
#    link point is never created and the directories of its parent are (see CREATE_BASE).
DOCROOT_CREATED="$(hp_reg_get website "$HOSTN" docroot_created)"; DOCROOT_CREATED="${DOCROOT_CREATED:-0}"
OWNER_UID="$(stat -c '%u' "$HOME_REAL")"
PARTS=()
if [ "$CREATE_BASE" != "$HOME_REAL" ]; then
  IFS=/ read -r -a PARTS <<< "${CREATE_BASE#"$HOME_REAL"/}"
fi
CUR="$HOME_REAL"
for i in "${!PARTS[@]}"; do
  CUR="$CUR/${PARTS[$i]}"
  [ ! -e "$CUR" ] && [ ! -L "$CUR" ] || continue
  mkdir -- "$CUR"
  hp_track_dir "$CUR"
  "$BIN/chown" -h "$OWNER_UID:$WEB_GROUP" "$CUR"
  chmod 2750 "$CUR"
  if [ "$LINK" = 0 ] && [ "$i" -eq $(( ${#PARTS[@]} - 1 )) ]; then
    DOCROOT_CREATED=1
  fi
  CHANGED=1
  hp_say "created ${PARTS[$i]}"
done

# 2. php-fpm pool for the account at this version (marked when this helper wrote it).
if [ -n "$PHP" ]; then
  if [ ! -f "$POOL" ]; then
    {
      cat <<POOL
$MARKER
[$ACCOUNT]
listen = $SOCK
listen.allowed_clients = 127.0.0.1
listen.group = "$WEB_GROUP"
listen.mode = 0660
user = "$ACCOUNT"
group = "$ACCOUNT"
pm = ondemand
pm.max_children = 4
pm.max_requests = 4000
pm.process_idle_timeout = 15s
rlimit_files = 131072
rlimit_core = unlimited
catch_workers_output = yes
env[HOSTNAME] = \$HOSTNAME
env[TMP] = $HOME_L/tmp
env[TMPDIR] = $HOME_L/tmp
env[TEMP] = $HOME_L/tmp
env[PATH] = /usr/local/bin:/usr/bin:/bin
php_admin_value[open_basedir] = $HOME_L/:/usr/local/lib/php/:/usr/share/php/
php_admin_value[session.save_path] = $HOME_L/tmp
php_admin_value[upload_tmp_dir] = $HOME_L/tmp
php_admin_value[disable_functions] = exec,shell_exec,system,passthru,proc_open,popen,pcntl_exec
POOL
    } > "$WORK/pool"
    hp_replace "$WORK/pool" "$POOL" || true
    POOL_CHANGED=1; CHANGED=1
    hp_say "pool written"
  fi
  if [ "$LINK" = 1 ]; then
    # A symlink switched in place behind Apache: Apache passes the unresolved docroot path, so OPcache would keep the previous
    # release's compiled script under it and a worker's realpath cache the old target. These lines make every request
    # resolve the link again (nginx avoids this with $realpath_root; Apache cannot).
    cp -- "$POOL" "$WORK/pool.link"
    grep -q 'opcache.validate_timestamps' "$WORK/pool.link" || printf 'php_admin_value[opcache.validate_timestamps] = 1\nphp_admin_value[opcache.revalidate_freq] = 0\n' >> "$WORK/pool.link"
    grep -q 'realpath_cache_size' "$WORK/pool.link" || printf 'php_admin_value[realpath_cache_size] = 0\n' >> "$WORK/pool.link"
    grep -q 'opcache.revalidate_path' "$WORK/pool.link" || printf 'php_admin_value[opcache.revalidate_path] = 1\n' >> "$WORK/pool.link"
    if hp_replace "$WORK/pool.link" "$POOL"; then
      POOL_CHANGED=1; CHANGED=1
      hp_say "symlink-switch opcache and realpath lines set in the pool"
    fi
  fi
fi

# 3. CWP's own per-domain record, so a later CWP vhost rebuild keeps this php version for the hostname.
WEBCONF="$HOME_DIR/.conf/webservers/$HOSTN.conf"
WEBCONF_CREATED="$(hp_reg_get website "$HOSTN" webconf_created)"; WEBCONF_CREATED="${WEBCONF_CREATED:-0}"
if [ -n "$PHP" ] && { [ ! -e "$WEBCONF" ] || [ "$WEBCONF_CREATED" = 1 ]; }; then
  printf '{\n    "apache_template-type": "php-fpm",\n    "apache_template-name": "default",\n    "php-fpm_ver": "%s",\n    "php-fpm": true,\n    "apache-main": true\n}\n' "$NN" > "$WORK/webconf"
  mkdir -p "$HOME_DIR/.conf/webservers"
  if hp_replace "$WORK/webconf" "$WEBCONF"; then
    WEBCONF_CREATED=1; CHANGED=1
    hp_say "cwp webserver record written"
  fi
fi

# 4. Vhost: a file this helper wrote is rendered again; a CWP-made one only gets (or loses) the php block.
FILES="$(hp_vhost_files "$HOSTN")"
[ -n "$FILES" ] || FILES="$VHOSTS/$HOSTN.conf"
for f in $FILES; do
  if [ ! -e "$f" ] || hp_is_managed "$f"; then
    cat > "$WORK/vhost.base" <<VHOST
$MARKER
<VirtualHost *:80>
	ServerName $HOSTN
	DocumentRoot $DOCROOT_L
	SuexecUserGroup $ACCOUNT $ACCOUNT
	<Directory "$DOCROOT_L">
		AllowOverride All
		Options -Indexes +FollowSymLinks
		Require all granted
	</Directory>
</VirtualHost>
VHOST
  else
    cp -- "$f" "$WORK/vhost.base"
  fi
  hp_strip_handler "$WORK/vhost.base" > "$WORK/vhost.stripped"
  if [ -n "$SOCK" ] && ! grep -qF -- "$SOCK" "$WORK/vhost.stripped"; then
    hp_insert_handler "$SOCK" < "$WORK/vhost.stripped" > "$WORK/vhost.final"
  else
    cp -- "$WORK/vhost.stripped" "$WORK/vhost.final"
  fi
  if hp_replace "$WORK/vhost.final" "$f"; then
    chmod 644 "$f"
    VHOST_CHANGED=1; CHANGED=1
    hp_say "vhost $(basename "$f") updated"
  fi
done

# 5. Both configurations must pass before anything is reloaded; a failure restores every edited file.
if [ "$VHOST_CHANGED" = 1 ] && ! hp_apache_test; then
  hp_die 1 "apachectl -t failed, restored"
fi
if [ -n "$PHP" ] && [ "$POOL_CHANGED" = 1 ] && ! hp_fpm_test "$NN"; then
  hp_die 1 "php-fpm $PHP test failed, restored"
fi
DIRTY=0
hp_reg_write website "$HOSTN" "docroot=$DOCROOT" "php=$NN" "link_root=$LINK" \
  "docroot_created=$DOCROOT_CREATED" "webconf_created=$WEBCONF_CREATED"
if [ "$POOL_CHANGED" = 1 ]; then
  "$BIN/systemctl" reload "php-fpm$NN"
  hp_say "php-fpm$NN reloaded"
fi
if [ "$VHOST_CHANGED" = 1 ]; then
  "$APACHECTL" graceful
  hp_say "apache graceful"
fi

if [ "$CHANGED" = 1 ]; then
  CHANGED_JSON=true
else
  CHANGED_JSON=false
fi
if [ -n "$PHP" ]; then
  hp_result "{\"changed\":$CHANGED_JSON,\"php_cli\":\"$PHP_CLI\"}"
else
  hp_result "{\"changed\":$CHANGED_JSON}"
fi
