#!/bin/bash
################################################################################
# Script Name: version/3.1.4/UPDATE.sh
# Description: Apply version 3.1.4 migrations:
#              - User Resource Limits (cgroups v2) via user-limit CLI
#              - Hosting Package & Plan CRUD with dynamic database column handling
#              - Streamlined Admin Packages management interface
#              - WebEngine & Multi-WebServer switching in Admin & User Domains
#              - Native Stack VirtualHosts and Caddy editor error suppression
#              - Updated Go static binaries for panel and admin backend
# 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.4] ${GREEN}✓${NC} $*"; }
warn() { echo -e "[3.1.4] ${YELLOW}!${NC} $*" >&2; }
[[ $EUID -eq 0 ]] || { echo "[3.1.4] 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.4" > /usr/local/hitechcloud/version 2>/dev/null || true
echo "3.1.4" > /etc/hitechcloud/version 2>/dev/null || true

# Ensure user-limit and plan scripts are executable in CLI directories
for base_cli in /usr/local/hitechcloudcli /usr/local/hitechcloudpanel/hitechcloudcli-scripts; do
    if [[ -d "$base_cli" ]]; then
        chmod +x "$base_cli"/user/*.sh "$base_cli"/plan/*.sh 2>/dev/null || true
    fi
done

# Ensure systemd user slice directory exists for cgroups resource limits
mkdir -p /etc/systemd/system/user-.slice.d 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.4 update steps completed successfully"
exit 0
