#!/bin/bash
################################################################################
# Script Name: version/3.1.2/UPDATE.sh
# Description: Apply version 3.1.2 migrations:
#              - MariaDB DSN RFC escaping for passwords with special characters
#              - Blank & static CMS application dispatcher and php_app preview
#              - APNIC RDAP IP & ASN lookup engine integration
#              - OpenLiteSpeed WebAdmin console on port 7080 with Let's Encrypt TLS
#              - Enforced FTP root directory path containment to /home/<user>/
#              - Remote screenshot service prioritisation over local probe
# 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.2] ${GREEN}✓${NC} $*"; }
warn() { echo -e "[3.1.2] ${YELLOW}!${NC} $*" >&2; }
[[ $EUID -eq 0 ]] || { echo "[3.1.2] This update must run as root." >&2; exit 1; }

# Update version files
echo "3.1.2" > /usr/local/hitechcloud/version 2>/dev/null || true
echo "3.1.2" > /etc/hitechcloud/version 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

# Sync OpenLiteSpeed admin SSL cert if available
if [[ -d "/usr/local/lsws/admin/conf" ]]; then
    HOSTNAME=$(cat /etc/hostname 2>/dev/null || hostname -f 2>/dev/null || hostname 2>/dev/null || echo "")
    if [[ -n "$HOSTNAME" && -f "/etc/hitechcloud/native/ssl/${HOSTNAME}/fullchain.pem" ]]; then
        mkdir -p /usr/local/lsws/admin/conf/cert 2>/dev/null || true
        cp -f "/etc/hitechcloud/native/ssl/${HOSTNAME}/fullchain.pem" /usr/local/lsws/admin/conf/cert/admin.crt 2>/dev/null || true
        cp -f "/etc/hitechcloud/native/ssl/${HOSTNAME}/privkey.pem" /usr/local/lsws/admin/conf/cert/admin.key 2>/dev/null || true
        chmod 600 /usr/local/lsws/admin/conf/cert/admin.key 2>/dev/null || true
        systemctl restart lsws 2>/dev/null || true
    fi
fi

ok "3.1.2 update steps completed successfully"
exit 0
