#!/bin/bash
################################################################################
# Script Name: version/3.1.7/UPDATE.sh
# Description: Apply version 3.1.7 migrations:
#              - Multi-tier sender avatar recognition without BIMI (Google S2 128px, DuckDuckGo)
#              - VMC (Verified Mark Certificate) & CMC (Common Mark Certificate) verified badges
#              - 256-hex-character platform site verification DNS TXT records
#              - WebRTC Audio DSP Voice Processing & FFmpeg 6.1.1 Composite Recording
#              - Assistant & Team Chat bugfix resolving _.map error
# 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.7] ${GREEN}✓${NC} $*"; }
warn() { echo -e "[3.1.7] ${YELLOW}!${NC} $*" >&2; }
[[ $EUID -eq 0 ]] || { echo "[3.1.7] 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.7" > /usr/local/hitechcloud/version 2>/dev/null || true
echo "3.1.7" > /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 services..."
    systemctl restart hitechmail-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.7 update steps completed successfully"
exit 0
