#!/bin/bash
################################################################################
# Script Name: version/3.0.9/UPDATE.sh
# Description: Apply version 3.0.9 migrations:
#              - Webmail Reseller Whitelabel with CNAME and Host dynamic branding
#              - Floating Assistant LiveChat integration and multi-provider AI chat stability
#              - Document collaboration with rich MS Word, PPT, Excel, and Markdown import/editing
#              - Files quota checking on upload for all account limits
#              - Background async SSL issuance in Admin 2087 and User 2083
#              - ZeroSSL, CA selector, and manual DNS verification challenge
#              - Acronis Cyber Cloud / Acronis Backup destination support
#              - Per-user WAF IP whitelist / proxy bypass exception rules
#              - Node.js, Laravel, Ruby, and Joomla developer toolkits
# 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.0.9] ${GREEN}✓${NC} $*"; }
warn() { echo -e "[3.0.9] ${YELLOW}!${NC} $*" >&2; }
[[ $EUID -eq 0 ]] || { echo "[3.0.9] This update must run as root." >&2; exit 1; }

# Update default backup.env template with Acronis destination block if needed
if [[ -f "/etc/hitechcloud/backups/backup.env" ]] && ! grep -q "ACRONIS_DATACENTER_URL" "/etc/hitechcloud/backups/backup.env"; then
    cat >> /etc/hitechcloud/backups/backup.env << 'EOF'

# --- Acronis Cyber Protect / Acronis Backup ---
# ACRONIS_DATACENTER_URL=https://cloud.acronis.com
# ACRONIS_CLIENT_ID=
# ACRONIS_CLIENT_SECRET=
# ACRONIS_TENANT_ID=
# ACRONIS_TARGET_PATH=backups
EOF
    ok "Added Acronis Backup configuration template to /etc/hitechcloud/backups/backup.env"
fi

# Ensure WAF directories exist with correct permissions
if [[ -d "/etc/hitechcloud/native/waf" ]]; then
    mkdir -p /etc/hitechcloud/native/waf/sites /etc/hitechcloud/native/waf/rules 2>/dev/null || true
    if id -u hitechwaf >/dev/null 2>&1; then
        chown -R hitechwaf:hitechwaf /etc/hitechcloud/native/waf 2>/dev/null || true
    fi
    ok "Verified WAF directories and permission ownership"
fi

ok "3.0.9 update steps completed successfully"
exit 0
