#!/bin/bash
################################################################################
# Script Name: version/2.1.25/UPDATE.sh
# Description: Put php_xray back, and stage the WordPress plugin.
# Company: hitechcloud.org
# Copyright (c) hitechcloud.org
################################################################################
#
# Two repairs for 2.1.24.
#
# php_xray registered "GET /api/php/xray/{domain}" beside the existing
# "GET /api/php/{version}/options". Go's ServeMux refuses two three-segment
# patterns whose wildcard sits in a different position - both match
# "/api/php/xray/options" and neither is more specific - and it refuses them by
# panicking at registration. So the panel did not fail to serve one page: it
# failed to start, on any server where both features were enabled, at the first
# restart after updating. The route has moved to /api/php-xray/ in 2.1.25.
#
# A server that hit this may have had php_xray removed from enabled_modules by
# hand to get the panel up again. This puts it back, but only where it was
# taken out - a server whose operator has never wanted it keeps not having it,
# which is why this checks the feature sets rather than adding it blindly.
#
# WP Helper was staged by INSTALL.sh only, and an update never runs INSTALL.sh
# - it unpacks the bundle and copies the CLI and the templates. So every
# updated server reported "WP Helper is not staged on this server" on each new
# WordPress. The panel now also looks in the unpacked bundle, and this stages
# it properly.
################################################################################

set -uo pipefail

GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'
ok()   { echo -e "[2.1.25] ${GREEN}✓${NC} $*"; }
warn() { echo -e "[2.1.25] ${YELLOW}!${NC} $*" >&2; }

[[ $EUID -eq 0 ]] || { echo "[2.1.25] This update must run as root." >&2; exit 1; }

readonly CONFIG=/etc/hitechcloud/hitechcloud/conf/hitechcloud.config
readonly FEATURES_DIR=/etc/hitechcloud/hitechcloud/features

# 1. php_xray, where a plan still grants it.
if [[ -f "$CONFIG" ]]; then
    granted=no
    for set in "$FEATURES_DIR"/*.txt; do
        [[ -f "$set" ]] || continue
        grep -qx 'php_xray' "$set" && { granted=yes; break; }
    done

    current=$(grep -E '^enabled_modules=' "$CONFIG" | head -1 | cut -d= -f2- | tr -d '"')
    if [[ "$granted" == yes ]] && ! grep -qE "(^|,)php_xray(,|$)" <<< "$current"; then
        current="${current},php_xray"
        awk -v line="enabled_modules=\"${current}\"" \
            '/^enabled_modules=/ { print line; next } { print }' "$CONFIG" > "${CONFIG}.new" &&
            cat "${CONFIG}.new" > "$CONFIG" && rm -f "${CONFIG}.new"
        ok "php_xray re-enabled; the route it collided with has moved"
    fi
fi

# 2. WP Helper, staged from the bundle this script came out of.
plugin_src="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." 2>/dev/null && pwd)/wp-helper"
if [[ -f "${plugin_src}/wp-helper.php" ]]; then
    dest=/etc/hitechcloud/wordpress/plugins/wp-helper
    # Mirrored, not merged: a file dropped from a newer version of the plugin
    # has to disappear from the staged copy too, or the autoloader will go on
    # loading a class file nothing references any more.
    if command -v rsync >/dev/null 2>&1; then
        mkdir -p "$dest" && rsync -a --delete "${plugin_src}/" "${dest}/"
    else
        rm -rf "$dest" && mkdir -p "$(dirname "$dest")" && cp -a "$plugin_src" "$dest"
    fi
    ok "WP Helper staged at ${dest}"
else
    warn "WP Helper is not in this bundle, so it was not staged."
fi

# The panel has to be restarted for a module list it read at startup, and the
# whole point of this release is that it can be.
systemctl restart hitechcloud >/dev/null 2>&1 || warn "Could not restart the panel - run: systemctl restart hitechcloud"
for _ in $(seq 1 20); do
    [[ "$(systemctl is-active hitechcloud 2>/dev/null)" == active ]] && break
    sleep 2
done
if [[ "$(systemctl is-active hitechcloud 2>/dev/null)" == active ]]; then
    ok "Panel restarted and running"
else
    warn "The panel is not running after the restart: systemctl status hitechcloud"
fi

hitechcloudcli cache-forget_features >/dev/null 2>&1 || warn "Could not clear the feature cache - run: hitechcloudcli cache-forget_features"

ok "2.1.25 update complete"
exit 0
