#!/bin/bash

# ==========================================================
# ProxMenux - A menu-driven script for Proxmox VE management
# ==========================================================
# Author      : MacRimi
# Copyright   : (c) 2024-2025 MacRimi
# License     : GPL-3.0 (https://github.com/MacRimi/ProxMenux/blob/main/LICENSE)
# Version     : 1.2
# Last Updated: 18/03/2026
# ==========================================================
# Description:
# Main entry point for ProxMenux.
# - Loads configuration and utility functions.
# - Detects if running in Beta Program mode (develop branch).
# - Checks for updates from the appropriate branch (main or develop).
# - In beta mode: compares beta_version.txt; notifies when a stable
#   release is available and prompts the user to switch.
# - Launches the main menu.
# ==========================================================

# ── Configuration ──────────────────────────────────────────
BASE_DIR="/usr/local/share/proxmenux"
LOCAL_SCRIPTS="$BASE_DIR/scripts"
CONFIG_FILE="$BASE_DIR/config.json"
CACHE_FILE="$BASE_DIR/cache.json"
UTILS_FILE="$BASE_DIR/utils.sh"
LOCAL_VERSION_FILE="$BASE_DIR/version.txt"
BETA_VERSION_FILE="$BASE_DIR/beta_version.txt"
VENV_PATH="/opt/googletrans-env"

REPO_MAIN="https://raw.githubusercontent.com/MacRimi/ProxMenux/main"
REPO_DEVELOP="https://raw.githubusercontent.com/MacRimi/ProxMenux/develop"

# ── Load utilities ─────────────────────────────────────────
[[ -f "$UTILS_FILE" ]] && source "$UTILS_FILE"

: "${LOCAL_SCRIPTS:=/usr/local/share/proxmenux/scripts}"

# ── Detect beta mode ───────────────────────────────────────
# Returns 0 (true) if this install is part of the beta program.
is_beta() {
    [[ -f "$CONFIG_FILE" ]] || return 1
    local beta_flag
    beta_flag=$(jq -r '.beta_program.status // empty' "$CONFIG_FILE" 2>/dev/null)
    [[ "$beta_flag" == "active" ]]
}

# ── Check for updates ──────────────────────────────────────
check_updates() {
    if is_beta; then
        check_updates_beta
    else
        check_updates_stable
    fi
}

# ── Stable update check (main branch) ─────────────────────
check_updates_stable() {
    local VERSION_URL="$REPO_MAIN/version.txt"
    local INSTALL_URL="$REPO_MAIN/install_proxmenux.sh"
    local INSTALL_SCRIPT="$BASE_DIR/install_proxmenux.sh"

    [[ ! -f "$LOCAL_VERSION_FILE" ]] && return 0

    local REMOTE_VERSION LOCAL_VERSION
    REMOTE_VERSION="$(curl -fsSL "$VERSION_URL" 2>/dev/null | head -n 1)"
    [[ -z "$REMOTE_VERSION" ]] && return 0

    LOCAL_VERSION="$(head -n 1 "$LOCAL_VERSION_FILE" 2>/dev/null)"
    [[ -z "$LOCAL_VERSION" ]] && return 0
    [[ "$LOCAL_VERSION" = "$REMOTE_VERSION" ]] && return 0

    if whiptail --title "$(translate 'Update Available')" \
                --yesno "$(translate 'New version available') ($REMOTE_VERSION)\n\n$(translate 'Do you want to update now?')" \
                10 60 --defaultno; then

        msg_warn "$(translate 'Starting ProxMenux update...')"

        if curl -fsSL "$INSTALL_URL" -o "$INSTALL_SCRIPT"; then
            chmod +x "$INSTALL_SCRIPT"
            bash "$INSTALL_SCRIPT" --update
            return 0
        fi
    fi
}

# ── Beta-mode update check (main + develop) ───────────────
# When the beta program is active, check BOTH channels. The stable check
# is delegated to check_updates_stable (same prompt, same installer). After
# that we only need the beta-specific part: develop vs beta_version.txt.
check_updates_beta() {
    # 1. Stable release on main — reuse the non-beta path.
    check_updates_stable

    # 2. Beta build on develop.
    [[ ! -f "$BETA_VERSION_FILE" ]] && return 0

    local REMOTE_BETA LOCAL_BETA
    REMOTE_BETA="$(curl -fsSL "$REPO_DEVELOP/beta_version.txt" 2>/dev/null | head -n 1)"
    LOCAL_BETA="$(head -n 1 "$BETA_VERSION_FILE" 2>/dev/null)"
    [[ -z "$REMOTE_BETA" || -z "$LOCAL_BETA" || "$LOCAL_BETA" = "$REMOTE_BETA" ]] && return 0
    [[ "$(printf '%s\n%s\n' "$LOCAL_BETA" "$REMOTE_BETA" | sort -V | tail -1)" = "$REMOTE_BETA" ]] || return 0

    if whiptail --title "Beta Update Available" \
                --yesno "A new beta build is available!\n\nInstalled beta : $LOCAL_BETA\nNew beta build : $REMOTE_BETA\n\nDo you want to update now?" \
                12 64 --defaultno; then

        msg_warn "Updating to beta build $REMOTE_BETA ..."

        local INSTALL_BETA_SCRIPT="$BASE_DIR/install_proxmenux_beta.sh"
        if curl -fsSL "$REPO_DEVELOP/install_proxmenux_beta.sh" -o "$INSTALL_BETA_SCRIPT"; then
            chmod +x "$INSTALL_BETA_SCRIPT"
            bash "$INSTALL_BETA_SCRIPT" --update
            return 0
        else
            msg_error "Could not download the beta installer from the develop branch."
        fi
    fi
}

# ── Main ───────────────────────────────────────────────────
main_menu() {
    local MAIN_MENU="$LOCAL_SCRIPTS/menus/main_menu.sh"
    exec bash "$MAIN_MENU"
}

load_language
initialize_cache
check_updates
main_menu
