#!/bin/bash
################################################################################
# Script Name: version/3.1.8/UPDATE.sh
# Description: Apply version 3.1.8 migrations:
#              - HiTechMeet Virtual Background & Gaussian Blur Engine
#              - Real-Time Skin Smoothing & Beauty Mode Filter
#              - Meeting Security Password Options & Random Passcode Generator
#              - Multi-Platform Live Streaming Egress (YouTube, Facebook, Twitch, RTMP)
#              - Media Stream Video Ingress into Video Conferencing
# 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.8] ${GREEN}✓${NC} $*"; }
warn() { echo -e "[3.1.8] ${YELLOW}!${NC} $*" >&2; }
[[ $EUID -eq 0 ]] || { echo "[3.1.8] 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.8" > /usr/local/hitechcloud/version 2>/dev/null || true
echo "3.1.8" > /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

# Synchronize Webmail assets and restart mail backend
if [[ -d "/usr/local/mail/webmail" ]]; then
    ok "Refreshing Webmail and HiTechMeet services..."
    systemctl restart hitechmail-webmail.service 2>/dev/null || true
    systemctl restart hitechcloud-meet.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, admin, and meet services to load updated configuration and routes
systemctl restart hitechcloud.service 2>/dev/null || true
systemctl restart hitechadmin.service 2>/dev/null || true
systemctl restart hitechcloud-meet.service 2>/dev/null || true

ok "3.1.8 update steps completed successfully"
