#!/bin/bash
################################################################################
# Script Name: version/3.1.9/UPDATE.sh
# Description: Apply version 3.1.9 migrations:
#              - Complete Booking Page Redesign with Meet-Style CardGrid
#              - Modal-Based Booking Page & Appointment Type Management
#              - HiTechMeet Video Conferencing One-Click Integration for Appointments
#              - Enhanced Visitor Booking Experience & 3-Step Scheduling Guide
#              - Webmail Meet Pre-join Lobby Stability Fix
#              - Comprehensive Bilingual Localization (VI / EN)
# 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.9] ${GREEN}✓${NC} $*"; }
warn() { echo -e "[3.1.9] ${YELLOW}!${NC} $*" >&2; }
[[ $EUID -eq 0 ]] || { echo "[3.1.9] 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.9" > /usr/local/hitechcloud/version 2>/dev/null || true
echo "3.1.9" > /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, Booking, 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.9 update steps completed successfully"
