#!/bin/bash
################################################################################
# Script Name: version/3.1.3/UPDATE.sh
# Description: Apply version 3.1.3 migrations:
#              - Enterprise & Package Lifecycle Management (CloudLinux, JetBackup, KernelCare, Softaculous, SitePad, CPGuard)
#              - Multi-Webserver management (Nginx, Apache, OpenLiteSpeed, Caddy, HAProxy, Traefik, Lighttpd, Cherokee, H2O)
#              - PHP Runtime packages (5.6, 7.4, 8.0, 8.1, 8.2, 8.3, 8.4, 8.5)
#              - WireGuard VPN Peer Manager & Client configuration distribution (.conf)
#              - APNIC RDAP IP/ASN Inspector
#              - Webmail attachment storage directory permissions hardening
# 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.3] ${GREEN}✓${NC} $*"; }
warn() { echo -e "[3.1.3] ${YELLOW}!${NC} $*" >&2; }
[[ $EUID -eq 0 ]] || { echo "[3.1.3] This update must run as root." >&2; exit 1; }

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

# Ensure Webmail storage directory permissions
if id -u hitechwebmail >/dev/null 2>&1; then
    mkdir -p /var/lib/hitechcloud/webmail-files /opt/hitechcloud/mailflow/backend/data 2>/dev/null || true
    chown -R hitechwebmail:hitechwebmail /var/lib/hitechcloud/webmail-files /opt/hitechcloud/mailflow/backend/data 2>/dev/null || true
    chmod -R 0770 /var/lib/hitechcloud/webmail-files /opt/hitechcloud/mailflow/backend/data 2>/dev/null || true
fi

# Ensure WireGuard directory exists
mkdir -p /etc/wireguard /etc/hitechcloud/wireguard 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

ok "3.1.3 update steps completed successfully"
exit 0
