#!/bin/bash
################################################################################
# Script Name: version/3.1.0/UPDATE.sh
# Description: Apply version 3.1.0 migrations:
#              - Native Stack VirtualHost editor with syntax testing (Nginx, Apache, OpenLiteSpeed/LiteSpeed)
#              - Document Root / Running Directory customization with Framework presets (Laravel/Symfony, Node, WordPress)
#              - Webmail AI Email Summarization on message list preview tiles
#              - Webmail AI Smart Reply Suggestions and Writing Assistant
#              - Subscription Manager & Label Manager modal support
#              - HiTechMeet Virtual Backgrounds and clean join URLs
#              - Security hardening: SQLi, RCE, Path Traversal, and isolated end-user permissions
# 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.0] ${GREEN}✓${NC} $*"; }
warn() { echo -e "[3.1.0] ${YELLOW}!${NC} $*" >&2; }
[[ $EUID -eq 0 ]] || { echo "[3.1.0] This update must run as root." >&2; exit 1; }

# Update version files
echo "3.1.0" > /usr/local/hitechcloud/version 2>/dev/null || true
echo "3.1.0" > /etc/hitechcloud/version 2>/dev/null || true

# 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

# Ensure WAF directories exist with correct permissions
if [[ -d "/etc/hitechcloud/native/waf" ]]; then
    mkdir -p /etc/hitechcloud/native/waf/sites /etc/hitechcloud/native/waf/rules 2>/dev/null || true
    if id -u hitechwaf >/dev/null 2>&1; then
        chown -R hitechwaf:hitechwaf /etc/hitechcloud/native/waf 2>/dev/null || true
    fi
fi

ok "3.1.0 update steps completed successfully"
exit 0
