#!/bin/bash
################################################################################
# Script Name: version/3.1.6/UPDATE.sh
# Description: Apply version 3.1.6 migrations:
#              - Email OTP Two-Factor Authentication (Admin & User panels)
#              - Passkeys (FIDO2 / WebAuthn) Multi-Origin & Proxy Fixes
#              - 2FA TOTP Time Drift / Clock Skew Tolerance
#              - Installation Repair Mechanism (hitechcloudcli update --repair)
#              - Admin UI Repair Action in Update Settings
# 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.6] ${GREEN}✓${NC} $*"; }
warn() { echo -e "[3.1.6] ${YELLOW}!${NC} $*" >&2; }
[[ $EUID -eq 0 ]] || { echo "[3.1.6] 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.6" > /usr/local/hitechcloud/version 2>/dev/null || true
echo "3.1.6" > /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

# Ensure database schema migration for Email OTP in MySQL panel database
if command -v mysql >/dev/null 2>&1; then
    mysql panel -e "
        SET @col_exists = (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'panel' AND TABLE_NAME = 'users' AND COLUMN_NAME = 'email_otp_enabled');
        SET @sql = IF(@col_exists = 0, 'ALTER TABLE users ADD COLUMN email_otp_enabled TINYINT(1) NOT NULL DEFAULT 0', 'SELECT 1');
        PREPARE stmt FROM @sql;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    " 2>/dev/null || true
fi

# Ensure database schema migration for Email OTP in SQLite admin database
for admin_db in /etc/hitechcloud/hitechadmin/users.db /etc/hitechcloud/hitechcloud/users.db; do
    if [[ -f "$admin_db" ]] && command -v sqlite3 >/dev/null 2>&1; then
        sqlite3 "$admin_db" "ALTER TABLE user ADD COLUMN email TEXT;" 2>/dev/null || true
        sqlite3 "$admin_db" "ALTER TABLE user ADD COLUMN email_otp_enabled BOOLEAN NOT NULL DEFAULT 0;" 2>/dev/null || true
    fi
done

# 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.6 update steps completed successfully"
exit 0
