#!/bin/bash
################################################################################
# Script Name: version/3.1.5/UPDATE.sh
# Description: Apply version 3.1.5 migrations:
#              - Multi-WebServer / WebEngine Quick Access in User Dashboard & Sidebar
#              - Webmail (:2096) React Blank Screen & Top-level Await Fix
#              - Webmail React Error Boundary with Auto Recovery
#              - Updated CLI dispatchers and backup synchronization
#              - Rebuilding Webmail and Panel Assets
# Company: hitechcloud.org
# Copyright (c) hitechcloud.org
################################################################################

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

# Update version files
mkdir -p /usr/local/hitechcloud /etc/hitechcloud 2>/dev/null || true
echo "3.1.5" > /usr/local/hitechcloud/version 2>/dev/null || true
echo "3.1.5" > /etc/hitechcloud/version 2>/dev/null || true

# Ensure all CLI scripts are executable
for base_cli in /usr/local/hitechcloudcli /usr/local/hitechcloudpanel/hitechcloudcli-scripts; do
    if [[ -d "$base_cli" ]]; then
        find "$base_cli" -name '*.sh' -exec chmod +x {} \; 2>/dev/null || true
    fi
done

# Ensure multiweb is present in enabled_modules
CONF_FILE="/etc/hitechcloud/hitechcloud/conf/hitechcloud.config"
if [[ -f "$CONF_FILE" ]]; then
    if ! grep -qE "^enabled_modules=.*(^|,)multiweb(,|$)" "$CONF_FILE"; then
        sed -i -E "s/^(enabled_modules=.*)$/\1,multiweb/" "$CONF_FILE" 2>/dev/null || true
        ok "Enabled 'multiweb' in hitechcloud.config"
    fi
fi

# Rebuild webmail frontend & restart webmail service if installed
if systemctl list-unit-files 2>/dev/null | grep -q '^hitechcloud-webmail\.service'; then
    ok "Updating Webmail service..."
    if command -v hitechcloudcli >/dev/null 2>&1; then
        hitechcloudcli native-webmail update >/dev/null 2>&1 || true
    fi
    systemctl restart hitechcloud-webmail.service 2>/dev/null || true
fi

# Rebuild web server configs if on native stack
if [[ -f "/etc/hitechcloud/native/native.conf" ]] && command -v hitechcloudcli >/dev/null 2>&1; then
    ok "Synchronizing native stack vhosts..."
    hitechcloudcli native-vhost rebuild --all --no-reload >/dev/null 2>&1 || true
    systemctl reload hitechcloud-nginx 2>/dev/null || true
    systemctl reload hitechcloud-apache 2>/dev/null || true
    systemctl reload hitechcloud-openlitespeed 2>/dev/null || true
    systemctl reload hitechcloud-frontend 2>/dev/null || true
fi

# Restart panel and admin services to load updated configuration and routes
systemctl restart hitechcloud.service 2>/dev/null || true
systemctl restart hitechadmin.service 2>/dev/null || true

ok "3.1.5 update steps completed successfully"
exit 0
