functions/github/Connect-GitHubOrg.ps1

function Connect-GitHubOrg
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [string] $OrgName
    )

    # When running in GitHub Actions we will need to ensure the
    # GitHub App is authenticated for the current GitHub Org
    if ($env:SSH_PRIVATE_KEY -and $env:GITHUB_APP_ID) {
        Write-Information "Getting access token for organisation: '$OrgName'"
        $accessToken = New-GitHubAppInstallationAccessToken -AppId $env:GITHUB_APP_ID `
                                                            -AppPrivateKey $env:SSH_PRIVATE_KEY `
                                                            -OrgName $OrgName
        
        if ($accessToken) {
            $env:GITHUB_TOKEN = $accessToken
        }
        else {
            throw "There was a problem obtaining an access token for '$OrgName' (GitHubAppId=$($env:GITHUB_APP_ID)"
        }
    }

    # Handle when insufficient environment variables are provided for GitHubApp auth
    elseif (!$env:GITHUB_APP_ID -xor $env:SSH_PRIVATE_KEY) {
        throw "Authenticating as a GitHubApp requires the environment variables SSH_PRIVATE_KEY and GITHUB_APP_ID to be set - to authenticate via the GitHub CLI ensure that neither of these variables are set."
    }

    # Support local/interactive testing by attempting to authenticate via the GitHub CLI
    else {
        if ($IsWindows) {
            $configPath = Join-Path $env:APPDATA "GitHub CLI"
        }
        else {
            $configPath = "~/.config/gh"
        }

        if (Test-Path $configPath) {
            $ghConfig = Get-Content (Join-Path $configPath "hosts.yml") -Raw | ConvertFrom-Yaml
            $env:GITHUB_TOKEN = $ghConfig."github.com".oauth_token
        }
        else {
            throw "To authenticate interactively, ensure you have the GitHub CLI installed and you have run the 'gh auth login' command."
        }
    }
}