PS.Git.psm1

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

        if (-not $env:LD_LIBRARY_PATH) {
            $env:LD_LIBRARY_PATH = $nativePath
        } else {
            # Write-Host "Setting LD_LIBRARY_PATH to $($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
            $distroName = $osRelease | ForEach-Object { if ($_ -match '^NAME=(.*)') { $matches[1].Trim('"') } }
            $distroVersion = $osRelease | ForEach-Object { if ($_ -match '^VERSION_ID=(.*)') { $matches[1].Trim('"') } }
            Write-Host "Detected Linux distribution: $distroName $distroVersion"
        }
    }
    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"
       initialize-Dll $dllPath
    }
    elseif ($IsLinux) {
       # just point the env path to the correct place
       Set-NativePaths
    }
    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 
    Write-Verbose "Loaded main DLL: $mainDllPath"
}
catch {
    throw "Failed to load main DLL: $mainDllPath. Error: $_"
}

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