#!/bin/bash
# Standardized .env loader function
# This ensures all scripts use the same ~/.env file consistently

# Load environment variables from ~/.env file
# Usage: source load-env.sh or . load-env.sh
load_env_file() {
    local env_file="${HOME}/.env"
    
    if [[ -f "$env_file" ]]; then
        # Source PROXMOX_* variables from ~/.env
        set -a
        source <(grep -E "^PROXMOX_" "$env_file" 2>/dev/null | sed 's/^/export /' || true)
        set +a
        
        # Ensure PROXMOX_TOKEN_SECRET is set from PROXMOX_TOKEN_VALUE for backwards compatibility
        if [[ -z "${PROXMOX_TOKEN_SECRET:-}" ]] && [[ -n "${PROXMOX_TOKEN_VALUE:-}" ]]; then
            export PROXMOX_TOKEN_SECRET="${PROXMOX_TOKEN_VALUE}"
        fi
        
        return 0
    else
        return 1
    fi
}

# Auto-load if sourced directly
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    # Script is being executed directly
    load_env_file
    if [[ $? -eq 0 ]]; then
        echo "✅ Loaded environment from ~/.env"
        echo "PROXMOX_HOST=${PROXMOX_HOST:-not set}"
        echo "PROXMOX_USER=${PROXMOX_USER:-not set}"
        echo "PROXMOX_TOKEN_NAME=${PROXMOX_TOKEN_NAME:-not set}"
        echo "PROXMOX_TOKEN_VALUE=${PROXMOX_TOKEN_VALUE:+***configured***}"
    else
        echo "❌ ~/.env file not found"
        exit 1
    fi
fi

