#!/bin/bash
################################################################################
# Script Name: version/3.0.1/UPDATE.sh
# Description: Re-check 3.0.0's findings, and name the edition out loud.
# Company: hitechcloud.org
# Copyright (c) hitechcloud.org
################################################################################
#
# Nothing to migrate. 3.0.1 is code: the editions are enforced where 3.0.0 only
# declared them, three injections are closed, and the updater no longer walks a
# million version numbers to get here.
#
# That last one is why this script matters more than its contents suggest. A
# server that has been stuck part-way through an update to 3.0.0 arrives here
# having run some of the earlier scripts and not others, so everything below is
# written to be safe to run twice and safe to run out of order.
#
# The edition notice at the end is the important line. 3.0.0 made a fresh
# install Community and 3.0.1 is the release that actually enforces it, so an
# operator whose server has no licence key is about to see forty-six features
# disappear. Being told that by the update is better than finding it in a
# customer's support ticket.
################################################################################

set -uo pipefail

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

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

# unit_exists NAME - without a pipe. `list-unit-files | grep -q` reports 141
# under pipefail, because grep exits on its first match and systemctl dies of
# SIGPIPE, so a match reads as a failure.
unit_exists() {
    local found
    found=$(systemctl list-unit-files --no-legend --no-pager "$1" 2>/dev/null)
    [[ -n "$found" ]]
}

# 1. The services 3.0.0 moved off the public internet, re-checked rather than
#    assumed - a server that never finished its 3.0.0 update did not get them.
OLS_ADMIN="/usr/local/lsws/admin/conf/admin_config.conf"
if [[ -f "$OLS_ADMIN" ]] && ! grep -qE '^[[:space:]]*address[[:space:]]+127\.0\.0\.1:' "$OLS_ADMIN"; then
    [[ -f "${OLS_ADMIN}.hitechcloud-original" ]] || cp -a "$OLS_ADMIN" "${OLS_ADMIN}.hitechcloud-original"
    sed -i -E 's|^([[:space:]]*address[[:space:]]+).*$|\1127.0.0.1:7080|' "$OLS_ADMIN"
    unit_exists 'hitechcloud-openlitespeed.service' && systemctl restart hitechcloud-openlitespeed >/dev/null 2>&1
    ok "OpenLiteSpeed's WebAdmin console moved to 127.0.0.1"
fi

if unit_exists 'varnish.service'; then
    systemctl disable --now varnish.service >/dev/null 2>&1 || true
    systemctl mask varnish.service >/dev/null 2>&1 || true
fi

for engine in elasticsearch opensearch; do
    conf="/etc/${engine}/${engine}.yml"
    [[ -f "$conf" ]] || continue
    grep -qE '^[[:space:]]*http\.host:[[:space:]]*127\.0\.0\.1' "$conf" && continue
    [[ -f "${conf}.hitechcloud-pre300" ]] || cp -a "$conf" "${conf}.hitechcloud-pre300"
    sed -i 's/^\([[:space:]]*http\.host\)/#\1/' "$conf"
    printf '\n# --- HiTechCloud Panel ---\n# http.host binds the REST API and overrides network.host.\nhttp.host: 127.0.0.1\n' >> "$conf"
    if unit_exists "${engine}.service" && [[ "$(systemctl is-active "$engine" 2>/dev/null)" == active ]]; then
        systemctl restart "$engine" >/dev/null 2>&1 || true
    fi
    ok "${engine}'s REST API moved to loopback"
done

# 2. The firewall's own key, which its preflight used to create as root.
if [[ -d /etc/hitechcloud/native/waf ]] && id -u hitechwaf >/dev/null 2>&1; then
    chown -R hitechwaf:hitechwaf /etc/hitechcloud/native/waf 2>/dev/null || true
    [[ -f /etc/hitechcloud/native/waf/secret.key ]] && chmod 640 /etc/hitechcloud/native/waf/secret.key 2>/dev/null
    [[ -d /var/log/hitechcloud/native/waf ]] && chown -R hitechwaf:hitechwaf /var/log/hitechcloud/native/waf 2>/dev/null || true
fi
if unit_exists 'hitechcloud-waf.service'; then
    systemctl daemon-reload >/dev/null 2>&1
    systemctl reset-failed hitechcloud-waf >/dev/null 2>&1
    systemctl restart hitechcloud-waf >/dev/null 2>&1
    sleep 3
    if [[ "$(systemctl is-active hitechcloud-waf 2>/dev/null)" == active ]]; then
        ok "Web application firewall is running"
    else
        warn "The firewall did not start. Check: journalctl -u hitechcloud-waf and /var/log/hitechcloud/native/waf/service.log"
    fi
fi

# 3. Which edition this server is, said plainly, because this is the release
#    where the answer starts to matter.
key=$(awk -F= '/^\[LICENSE\]/{s=1;next} /^\[/{s=0} s&&/^[[:space:]]*key[[:space:]]*=/{gsub(/^[[:space:]]+|[[:space:]]+$/,"",$2);print $2;exit}' \
      /etc/hitechcloud/hitechcloud/conf/hitechcloud.config 2>/dev/null)

if [[ -n "$key" ]]; then
    ok "This server holds a licence key: Enterprise. Nothing changes for it."
else
    warn "This server has no licence key, so it is Community - and 3.0.1 is the release that enforces that."
    warn "  Three hosting accounts, fifty domains, and the admin panel on 2087 closed."
    warn "  The Enterprise features are no longer served: email accounts, webmail, FTP, PostgreSQL,"
    warn "  containers, the web terminal, the firewall page and the JSON API among them."
    warn "  Everything else keeps working, on the hosting panel at 2083 - which is now also where"
    warn "  PHP versions are managed, and where a licence key is entered."
    warn "  Add a key with: hitechcloudcli license <key>"
fi

ok "3.0.1 update complete"
exit 0
