Module/DevOps/New-BCSDevOpsGitHubServiceConnection.ps1

<#
.SYNOPSIS
    Creates a new Service Connection to GitHub in Azure DevOps.
 
.DESCRIPTION
    This function creates a new Service Connection to GitHub in Azure DevOps using the Service Endpoints API.
 
.PARAMETER organization
    The Azure DevOps organization name.
 
.PARAMETER project
    The Azure DevOps project name.
 
.PARAMETER pat
    The Azure DevOps Personal Access Token.
 
.PARAMETER githubPat
    The GitHub Personal Access Token.
 
.PARAMETER githubUsername
    Your GitHub username.
 
.PARAMETER repoName
    The name of the GitHub repository.
 
.PARAMETER connectionName
    The desired name for the Azure DevOps Service Connection.
 
.EXAMPLE
    New-GitHubServiceConnection -organization "YourOrganization" -project "YourProject" -pat "YourAzureDevOpsPAT" `
        -githubPat "YourGitHubPAT" -githubUsername "YourGitHubUsername" -repoName "YourRepoName" -connectionName "YourConnectionName"
#>


function New-BCSDevOpsGitHubServiceConnection {
    param (
        [string]$organization = "BrightComSolutions",
        [string]$devOpsPAT,
        [string]$githubPAT,  # GitHub Personal Access Token
        [string]$githubUsername,
        [string]$repoName,
        [string]$projectName,
        [string]$serviceConnectionName = "github.com_BrightCom-dev"
    )

    $url = "https://dev.azure.com/$organization/_apis/serviceendpoint/endpoints?api-version=6.0-preview.4"

    $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes((":$devOpsPAT")))

    $projectId = (Get-BCSDevOpsProject -projectName $projectName -sourcePat (Get-BCSSecureString -InputString $devOpsPAT)).id

    $hashtable = @{
        name = "release"
        type = "github"
        url = "https://github.com"
        authorization = @{
            scheme = "PersonalAccessToken"
            parameters = @{
                accessToken = $githubPAT
            }
        }
        serviceEndpointProjectReferences = @(
            @{
                projectReference = @{
                    id = $projectId
                    name = "github"
                }
                name = $serviceConnectionName
            }
        )
    }
    
    # To convert to JSON if needed
    $body = $hashtable | ConvertTo-Json -Depth 10

    try {
        $response = Invoke-RestMethod -Uri $url -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method Post -Body $body -ContentType "application/json"
        Write-Host "Service Connection created successfully. Connection Id: $($response.id)"
    } catch {
        Write-Host "Error creating Service Connection: $($_.Exception)"
    }
}

Export-ModuleMember -Function New-BCSDevOpsGitHubServiceConnection