#!/bin/bash
################################################################################
# Script Name: version/3.3.0/UPDATE.sh
# Description: Apply version 3.3.0 migrations:
#              - Packages & Apps (hitechcloudcli enterprise) with background jobs
#              - Docker as an application (rootless Podman per account)
#              - MongoDB (BETA), VPN (WireGuard peers) and IP pool modules
#              - Caddy / Lighttpd / H2O / Cherokee WebEngines, HAProxy / Traefik
#              - Hourly RDAP enrichment of access-log IPs (top visitors)
#              - TasksMax (PIDs) derived from plan RAM, /home/<user>/TasksMax override
#              - Go quota-report; utils synced from the new CLI tree
#              - Installs the modules 3.3.0 adds (Docker, extra WebEngines,
#                MongoDB, WireGuard, monitoring, S3) on updated servers
# Company/Brand: HiTechCloud by Pho Tue SoftWare Solutions JSC
################################################################################

set -uo pipefail
GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'
ok()   { echo -e "[3.3.0] ${GREEN}✓${NC} $*"; }
warn() { echo -e "[3.3.0] ${YELLOW}!${NC} $*" >&2; }
[[ $EUID -eq 0 ]] || { echo "[3.3.0] This update must run as root." >&2; exit 1; }

VERSION="3.3.0"
SRC="${HITECHCLOUD_SRC:-/opt/hitechcloud}"
CLI_DIR="/usr/local/hitechcloudcli"
PANEL_CONF="/etc/hitechcloud/hitechcloud/conf/hitechcloud.config"

mkdir -p /usr/local/hitechcloud /etc/hitechcloud 2>/dev/null || true
echo "$VERSION" > /usr/local/hitechcloud/version 2>/dev/null || true
echo "$VERSION" > /etc/hitechcloud/version 2>/dev/null || true

# 1. CLI utilities: the new native/*.sh scripts, lib/native.sh and
#    enterprise.sh. The regular updater already copied the tree; this makes
#    sure of it on an install that pulls its own checkout.
if [[ -d "${SRC}/hitechcloudcli" ]]; then
    rsync -a --exclude '.git' "${SRC}/hitechcloudcli/" "${CLI_DIR}/" 2>/dev/null || cp -a "${SRC}/hitechcloudcli/." "${CLI_DIR}/"
    ok "CLI scripts synced from ${SRC}/hitechcloudcli"
fi
find "$CLI_DIR" -name '*.sh' -exec chmod +x {} \; 2>/dev/null || true
for s in native/docker.sh native/mongodb.sh native/wireguard.sh native/ipmanager.sh enterprise.sh; do
    [[ -f "${CLI_DIR}/${s}" ]] && ok "${s} present" || warn "${s} missing under ${CLI_DIR} - re-run the updater"
done

# 2. Modules the catalogue gained: the server-wide switch has to list them
#    or no plan can grant them.
if [[ -f "$PANEL_CONF" ]]; then
    for m in mongodb vpn docker; do
        if ! grep -qE "^enabled_modules=.*\b${m}\b" "$PANEL_CONF"; then
            sed -i "/^enabled_modules=/ s/\"$/,${m}\"/; /^enabled_modules=/ s/,,/,/" "$PANEL_CONF"
            ok "enabled_modules += ${m}"
        fi
    done
fi

# 3. Native stack: templates for the new engines, units, the RDAP timer,
#    and the PID ceiling recalculated from plan RAM for every account.
if [[ -f /etc/hitechcloud/native/native.conf ]] && command -v hitechcloudcli >/dev/null 2>&1; then
    if [[ -d "${SRC}/hitechcloudpanel/configuration-native" ]]; then
        cp -a "${SRC}/hitechcloudpanel/configuration-native/." /etc/hitechcloud/native/templates/ 2>/dev/null && ok "Templates refreshed"
    fi
    for u in hitechcloud-rdap.service hitechcloud-rdap.timer; do
        [[ -f "/etc/hitechcloud/native/templates/systemd/${u}" ]] && cp -f "/etc/hitechcloud/native/templates/systemd/${u}" /etc/systemd/system/
    done
    systemctl daemon-reload
    systemctl enable --now hitechcloud-rdap.timer >/dev/null 2>&1 && ok "hitechcloud-rdap.timer enabled"
    hitechcloudcli native-limits apply-all >/dev/null 2>&1 && ok "TasksMax recalculated from plan RAM for every account" || warn "native-limits apply-all did not run cleanly"
    grep -q '^DOCKER_APP=' /etc/hitechcloud/native/native.conf || echo 'DOCKER_APP=off' >> /etc/hitechcloud/native/native.conf
    mkdir -p /etc/hitechcloud/native/ips /etc/hitechcloud/native/accounts /var/log/hitechcloud/enterprise /etc/hitechcloud/enterprise
fi

# 4. Install what 3.3.0 adds, so an updated server has the same modules as a
#    fresh one: the Docker application, the extra WebEngines, MongoDB,
#    WireGuard, Sentinel monitoring and the S3 backup client. Each goes
#    through Packages & Apps' own installer (log per module under
#    /var/log/hitechcloud/enterprise/), in the foreground so this update does
#    not finish before they do. A module that is already present is left
#    alone; one that cannot be installed on this OS (H2O and Cherokee are not
#    packaged everywhere) is reported and skipped. HITECHCLOUD_UPDATE_SKIP_APPS=1
#    skips the whole step; HITECHCLOUD_UPDATE_APPS="docker caddy" limits it.
if [[ -f /etc/hitechcloud/native/native.conf ]] && command -v hitechcloudcli >/dev/null 2>&1 && [[ "${HITECHCLOUD_UPDATE_SKIP_APPS:-0}" != "1" ]]; then
    APPS="${HITECHCLOUD_UPDATE_APPS:-docker caddy lighttpd h2o cherokee mongodb wireguard monitoring s3 ipmanager}"
    for app in $APPS; do
        state=$(hitechcloudcli enterprise "$app" status --json 2>/dev/null | tail -n1 | grep -o '"status":"[a-z_]*"' | cut -d'"' -f4)
        if [[ "$state" == "active" || "$state" == "inactive" ]]; then
            ok "${app}: already installed (${state})"
            continue
        fi
        echo "[3.3.0] installing ${app} ..."
        if hitechcloudcli enterprise "$app" install >> "/var/log/hitechcloud/enterprise/${app}.log" 2>&1; then
            ok "${app}: installed"
        else
            warn "${app}: install did not complete - see /var/log/hitechcloud/enterprise/${app}.log (re-run from HiTechAdmin > Services > Packages & Apps)"
        fi
    done
    # The engines just added take part in Multi-WebServer Hosting once their
    # units and master configs are in place.
    hitechcloudcli native-multiweb repair >/dev/null 2>&1 && ok "WebEngines re-wired" || warn "native-multiweb repair reported a problem; check: hitechcloudcli native-multiweb status"
fi

# 5. The Rust CLI (fast listings for Packages & Apps, WireGuard, IP pool,
#    quota report). Optional: every caller falls back to shell without it.
if [[ ! -x /usr/local/bin/hitechcloud-rustcli ]]; then
    arch=$(uname -m); case "$arch" in x86_64) arch=amd64 ;; aarch64) arch=arm64 ;; esac
    if curl -fsSL --retry 2 --connect-timeout 15 "https://github.com/hitechcloud-vietnam/HiTechCloud-Panel/releases/download/v${VERSION}/hitechcloud-rustcli-linux-${arch}" -o /tmp/hitechcloud-rustcli 2>/dev/null \
       || curl -fsSL --retry 2 --connect-timeout 15 "https://mirrors.hitechcloud.org/releases/latest/hitechcloud-rustcli-linux-${arch}" -o /tmp/hitechcloud-rustcli 2>/dev/null; then
        install -m 755 /tmp/hitechcloud-rustcli /usr/local/bin/hitechcloud-rustcli && ok "hitechcloud-rustcli installed"
    else
        warn "hitechcloud-rustcli not downloaded (shell fallbacks stay in use)"
    fi
    rm -f /tmp/hitechcloud-rustcli
fi

# 6. First quota report (Rust port when present, else the Go one; the timer keeps it fresh).
if command -v hitechcloud-rustcli >/dev/null 2>&1; then
    hitechcloud-rustcli quota-report >/dev/null 2>&1 && ok "quota_report.json regenerated (rustcli)" || true
fi
if [[ -x /usr/local/bin/hitechcloud ]]; then
    /usr/local/bin/hitechcloud quota-report >/dev/null 2>&1 && ok "quota_report.json regenerated" || true
fi

# 7. Both panels read their catalogue and units at startup.
systemctl restart hitechcloud >/dev/null 2>&1 || true
systemctl restart hitechadmin >/dev/null 2>&1 || true
ok "Version ${VERSION} applied. Packages & Apps: https://<server>:2087/services/apps"
