Load-EnvVariables.ps1

# ========================================
# Load Environment Variables from .env file
# ========================================
# Helper script to load .env variables for Send-MailAlert testing
# Usage: . .\Load-EnvVariables.ps1
# ========================================

[CmdletBinding()]
param(
    [Parameter(Mandatory = $false)]
    [string]$EnvFilePath = "$PSScriptRoot\.env"
)

Write-Host "Loading environment variables from: $EnvFilePath" -ForegroundColor Cyan

if (-not (Test-Path $EnvFilePath)) {
    Write-Error "Environment file not found: $EnvFilePath"
    return
}

try {
    # Read and parse .env file
    $envContent = Get-Content $EnvFilePath -ErrorAction Stop
    $loadedVars = 0
    
    foreach ($line in $envContent) {
        # Skip comments and empty lines
        if ($line -match '^\s*#' -or $line -match '^\s*$') {
            continue
        }
        
        # Parse KEY=VALUE format
        if ($line -match '^([^=]+)=(.*)$') {
            $key = $Matches[1].Trim()
            $value = $Matches[2].Trim()
            
            # Remove quotes if present
            if ($value -match '^"(.*)"$' -or $value -match "^'(.*)'$") {
                $value = $Matches[1]
            }
            
            # Set environment variable
            Set-Variable -Name $key -Value $value -Scope Global
            Write-Verbose "Loaded: $key = $value"
            $loadedVars++
        }
    }
    
    Write-Host "Successfully loaded $loadedVars environment variables" -ForegroundColor Green
    
    # Display loaded configuration (without sensitive data)
    Write-Host "`nLoaded Configuration:" -ForegroundColor Yellow
    Write-Host " SMTP Server: $SMTP_SERVER" -ForegroundColor Gray
    Write-Host " SMTP Port: $SMTP_PORT" -ForegroundColor Gray
    Write-Host " Use SSL: $SMTP_USE_SSL" -ForegroundColor Gray
    Write-Host " From: $SMTP_FROM" -ForegroundColor Gray
    Write-Host " To: $SMTP_TO" -ForegroundColor Gray
    Write-Host " Username: $(if ($SMTP_USERNAME) { $SMTP_USERNAME } else { 'Not configured (Anonymous)' })" -ForegroundColor Gray
    Write-Host " Password: $(if ($SMTP_PASSWORD) { '*' * $SMTP_PASSWORD.Length } else { 'Not required (Anonymous)' })" -ForegroundColor Gray
    Write-Host " Test Mode: $TEST_MODE" -ForegroundColor Gray
    Write-Host " Log Path: $LOG_PATH" -ForegroundColor Gray
    Write-Host " Pattern: $ALERT_PATTERN" -ForegroundColor Gray
    
} catch {
    Write-Error "Failed to load environment variables: $_"
}

# Helper function to create PSCredential from loaded variables
function Get-SMTPCredential {
    [CmdletBinding()]
    param()
    
    if (-not $SMTP_USERNAME -or -not $SMTP_PASSWORD) {
        Write-Verbose "SMTP authentication not configured - will use anonymous SMTP"
        return $null
    }
    
    try {
        $securePassword = ConvertTo-SecureString $SMTP_PASSWORD -AsPlainText -Force
        $credential = New-Object System.Management.Automation.PSCredential($SMTP_USERNAME, $securePassword)
        return $credential
    } catch {
        Write-Error "Failed to create credential: $_"
        return $null
    }
}

# Helper function to test the Send-MailAlert function with loaded environment variables
function Test-MailAlertWithEnv {
    [CmdletBinding()]
    param(
        [switch]$TestMode = [bool]::Parse($TEST_MODE),
        [string]$CustomPattern,
        [string]$CustomLogPath
    )
    
    # Use environment variables or provided parameters
    $pattern = if ($CustomPattern) { $CustomPattern } else { $ALERT_PATTERN }
    $logPath = if ($CustomLogPath) { $CustomLogPath } else { $LOG_PATH }
    
    # Split recipients
    $recipients = $SMTP_TO -split ',' | ForEach-Object { $_.Trim() }
    
    # Get credentials (optional for anonymous SMTP)
    $cred = Get-SMTPCredential
    if (-not $cred) {
        Write-Host "Using anonymous SMTP (no authentication)" -ForegroundColor Yellow
    } else {
        Write-Host "Using authenticated SMTP" -ForegroundColor Green
    }
    
    # Build parameters for Send-MailAlert
    $params = @{
        From = $SMTP_FROM
        To = $recipients
        SmtpServer = $SMTP_SERVER
        Port = [int]$SMTP_PORT
        UseSsl = [bool]::Parse($SMTP_USE_SSL)
        Subject = $EMAIL_SUBJECT
        LogPath = $logPath
        Pattern = $pattern
        IncludeLogContent = [bool]::Parse($INCLUDE_LOG_CONTENT)
        MaxLines = [int]$MAX_LINES
        AttachLog = [bool]::Parse($ATTACH_LOG)
        TestMode = $TestMode
    }
    
    # Add credentials only if available (optional authentication)
    if ($cred) {
        $params.Credential = $cred
    }
    
    Write-Host "`nTesting Send-MailAlert with environment configuration..." -ForegroundColor Cyan
    
    # Call the function (assuming it's already loaded)
    if (Get-Command Send-MailAlert -ErrorAction SilentlyContinue) {
        Send-MailAlert @params
    } else {
        Write-Error "Send-MailAlert function not found. Please load the function first:"
        Write-Host ". .\Send-MailAlert_function.ps1" -ForegroundColor Yellow
    }
}

Write-Host "`nHelper Functions Available:" -ForegroundColor Cyan
Write-Host " Get-SMTPCredential - Create PSCredential from env variables" -ForegroundColor Gray
Write-Host " Test-MailAlertWithEnv - Test Send-MailAlert with loaded config" -ForegroundColor Gray
Write-Host "`nExample Usage:" -ForegroundColor Cyan
Write-Host " . .\Send-MailAlert_function.ps1 # Load the function first" -ForegroundColor Gray
Write-Host " Test-MailAlertWithEnv -TestMode # Test without sending emails" -ForegroundColor Gray