PS.Git.psm1

function _SetNativePaths {
    if ($IsLinux) {
        $nativePath = Join-Path $PSScriptRoot '../runtimes/linux-x64/native' | Resolve-Path | Select-Object -ExpandProperty Path

        if (-not $env:LD_LIBRARY_PATH) {
            $env:LD_LIBRARY_PATH = $nativePath
        }
        elseif (-not ($env:LD_LIBRARY_PATH -split ':' | Where-Object { $_ -eq $nativePath })) {
            $env:LD_LIBRARY_PATH = "$nativePath:${env:LD_LIBRARY_PATH}"
        }
    }
}

function initialize-Dll {
    param(
        [string]$dllPath
    )
    if (-not (Test-Path $dllPath)) {
        throw "DLL not found: $dllPath"
    }
    try {
        [System.Runtime.InteropServices.NativeLibrary]::Load($dllPath) | Out-Null
        Write-Host "Loaded DLL: $dllPath"
    }
    catch {
        throw "Failed to load DLL: $dllPath. Error: $_"
    }
}

function Initialize-NativeGitLibrary {
    # Detect OS and architecture
    if ($IsWindows) {
        $os = 'Windows'
    }
    elseif ($IsLinux) {
        $os = 'Linux'
        # Optional: Detect specific Linux distro (like Ubuntu)
        if (Test-Path /etc/os-release) {
            $osRelease = Get-Content /etc/os-release | ConvertFrom-StringData -Delimiter '='
            $distroName = $osRelease['NAME']
            $distroVersion = $osRelease['VERSION_ID']
            Write-Verbose "Detected Linux distribution: $distroName $distroVersion"
            if ($distroName -notlike '*Ubuntu*' -or $distroVersion -notin @('20.04', '22.04')) {
                throw "Unsupported Linux distribution: $distroName $distroVersion. Only Ubuntu 20.04 and 22.04 are officially supported."
            }
            _SetNativePaths
        }
    }
    else {
        throw "Unsupported operating system. Only Windows and Ubuntu x64 are supported."
    }

    $arch = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture
    if ($arch -ne 'X64') {
        throw "Unsupported architecture: $arch. Only x64 is supported."
    }

    # Build native library path
    $basePath = Join-Path $PSScriptRoot "runtimes"
    if ($IsWindows) {
       $dllPath = Join-Path $basePath "win-x64\native\git2-3f4182d.dll"
       Write-Host "Loading Windows lib2git"    
       initialize-Dll $dllPath
    }
    elseif ($IsLinux) {
        $dllPath = Join-Path $basePath "linux-x64/native/libgit2-3f4182d.so"
        Write-Host "Loading linux lib2git" 
        initialize-Dll $dllPath 
    }
    else {
       Write-Host "Unsupported OS"  
    }
}

# Call it immediately when the module is imported
Initialize-NativeGitLibrary

# Load the main DLL
$mainDllPath = Join-Path $PSScriptRoot "PS.Git.dll"
if (-not (Test-Path $mainDllPath)) {
    throw "Main DLL not found: $mainDllPath"
}

try {
    Import-Module -Name $mainDllPath -Verbose
    Write-Verbose "Loaded main DLL: $mainDllPath"
}
catch {
    throw "Failed to load main DLL: $mainDllPath. Error: $_"
}

# Export your functions here
Export-ModuleMember -Cmdlet * -Alias *