modules/runner/functions.psm1

function Invoke-GitURL {

    param(
        [Parameter(mandatory)]
        [string]$url,
        [Parameter(mandatory)]
        [string]$token,
        [hashtable]$param
    )

    <# Collect $(Vars - 'RE_') and Values
$Parameters = @{ }
foreach ($Variable in (Get-Item "Variable:_*") ) {
    $Name = $Variable.Name -replace ('_', '')
    if ($Show_Variable_Output) {
        Write-Output "[Name]($Name) | [Value]($($Variable.Value))"
    }
    $Parameters[$Name] = $Variable.Value
}
if ($Parameters -eq $null) { $Parameters = 'None' } # For Verbose Logging
#>


    # [config] settings
    $gitserver = "https://gitlab.com"
    $download_dir = "/git-runner/scripts/downloads"

    # [check url] pipeline
    if (-not ($url -like "$gitserver/*")) {
        Write-Error "URL Must Be From This Git Source: $gitserver`n[$url]"
        break
    }
    else {
        # Check Default Directory
        if (-not (test-path $download_dir)) {
            New-Item $download_dir -ItemType 'Directory' | Out-Null
        }
        Set-Location $download_dir
    }

    # [group info] on project
    if ($token -notlike "*:*") {
        $project = ($url -replace ("//", "/")).split('/') | Where-Object { $_ -ne '' }
        $group = $project[2]
        $project = $project[3]
        $id = (Invoke-RestMethod -Headers @{"PRIVATE-TOKEN" = "$token" } -SessionVariable 'gitsession' `
                -Uri "$gitserver/api/v4/search?scope=projects&search=$project" -Verbose:$false) | where-object { $_.path_with_namespace -eq "$group/$project" } `
        | Select-Object -ExpandProperty 'id'
    }

    # [blob & raw] file url
    if (($url -like "*/-/blob/*") -or ($url -like "*/-/raw/*")) {
        # get file info
        $url = ($url).replace("/-/blob/", "/-/raw/")
        $info = (($url).split("/-/raw")[1]).split("/") | Where-Object { $_ -ne '' }
        $ref = $info[0]
        $path = (($info | select-object -Skip 1) -join '/').replace('/', '%2F').replace('.', '%2E')

        # download file
        Invoke-RestMethod -WebSession $gitsession -Uri "$gitserver/api/v4/projects/$id/repository/files/$path/raw?ref=$ref" `
            -OutFile "$download_dir/$($info | Select-Object -Last 1)" -Verbose:$false
        Write-Output "Git-Run: $($info | Select-Object -Last 1) >> [$download_dir/$($info | Select-Object -Last 1)]"
        Write-Output " "
    }
    else {
        break
    }

    # Verify Local File Extension
    $newfile_path = "$download_dir/$($info | Select-Object -Last 1)"
    $file_type = (Get-ItemProperty "$newfile_path").extension

    # Powershell
    if ($file_type -eq '.ps1') {
        # Unblock-File "$newfile_path" [needs chmod +x & unblock (OS Check)]
        if ($param) {
            $code = (& "$newfile_path" @param)
        }
        else {
            $code = (& "$newfile_path")
        }
        exit $code
    }

    # Python [later]
}

function Receive-GitURL {
    param(
        [Parameter(mandatory)]
        [string]$url,
        [Parameter(mandatory)]
        [string]$token
    )

    # [config] settings
    $gitserver = "https://gitlab.com"
    $download_dir = "/git-runner/scripts/downloads"

    # [check url] pipeline
    if (-not ($url -like "$gitserver/*")) {
        Write-Error "URL Must Be From This Git Source: $gitserver`n[$url]"
        break
    }
    else {
        # Check Default Directory
        if (-not (test-path $download_dir)) {
            New-Item $download_dir -ItemType 'Directory'
        }
        Set-Location $download_dir
    }

    # [group info] on project
    if ($token -notlike "*:*") {
        $project = ($url -replace ("//", "/")).split('/') | Where-Object { $_ -ne '' }
        $group = $project[2]
        $project = $project[3]
        $id = (Invoke-RestMethod -Headers @{"PRIVATE-TOKEN" = "$token" } -SessionVariable 'gitsession' `
                -Uri "$gitserver/api/v4/search?scope=projects&search=$project") | where-object { $_.path_with_namespace -eq "$group/$project" } `
        | Select-Object -ExpandProperty 'id'
    }

    # [tree] repo url
    if (($url -like "*/-/tree/*") -or (($url -notlike "*.git") -and (($url -notlike "*/-/blob/*") -and ($url -notlike "*/-/raw/*")))) {
        if ($url -notlike "*/-/tree/*") {
            $path = ($url).split("$gitserver/$group/")[1]
            if ($path -ne $project) {
                $files = Invoke-RestMethod -WebSession $gitsession -Uri "$gitserver/api/v4/projects/$id/repository/tree?recursive=true&ref=master&path=$path"
            }
            else {
                $files = Invoke-RestMethod -WebSession $gitsession -Uri "$gitserver/api/v4/projects/$id/repository/tree?recursive=true&ref=master"
            }
        }
        else {
            $info = (($url).split("/-/tree")[1]).split("/") | Where-Object { $_ -ne '' }
            $files = Invoke-RestMethod -WebSession $gitsession -Uri "$gitserver/api/v4/projects/$id/repository/tree?recursive=true&ref=$($info[0])&path=$(($info | select-object -Skip 1) -join '/')"
        }
        if ($files) {
            foreach ($file in ($files | Where-Object { $_.type -eq 'blob' })) {
                $ref = $file.path.Split('/')
                # test/create path
                if ($ref.count -ne 1) {
                    if (-not (Test-Path "$($ref.Split('/')[0..($ref.count - 2)] -join '/')")) {
                        New-Item "$($ref.Split('/')[0..($ref.count - 2)] -join '/')" -ItemType 'Directory' | Out-Null
                        # download file
                        Invoke-RestMethod -WebSession $gitsession -Uri "$gitserver/api/v4/projects/$id/repository/files/$($file.path.replace('/','%2F').replace('.','%2E'))/raw?ref=master" `
                            -OutFile "$download_dir/$($file.path)"
                        Write-Output "$($file.path) >> [$download_dir/$($file.path)]"
                    }
                }
                else {
                    if (-not (Test-Path "$download_dir/$path")) {
                        New-Item "$download_dir/$path" -ItemType 'Directory' | Out-Null
                    }
                    # download file
                    Invoke-RestMethod -WebSession $gitsession -Uri "$gitserver/api/v4/projects/$id/repository/files/$($file.path.replace('/','%2F').replace('.','%2E'))/raw?ref=master" `
                        -OutFile "$download_dir/$path/$($file.path)"
                    Write-Output "$($file.path) >> [$download_dir/$path/$($file.path)]"
                }
            }
        }
        else {
            Write-Error "No Directory/Files Found: [$url]"
        }
    }

    # [.git] clone url
    if ($url -like "*.git") {
        $project = ($url).split("//")[1]
        if ($token -notlike "*:*") {
            Write-Error "Git Clone Tokens Must Equal: [username:token]"
            break
        }
        else {
            $name = (($project).split("/") | Select-Object -Last 1).Replace(".git", "")
            if (-not (Test-Path $name)) {
                git clone "https://${token}@${project}" -q -n
            }
            else {
                Set-Location $name
                git pull "https://${token}@${project}" -q -n
            }
            Write-Output "${project} >> [$download_dir/${project}]"
        }
    }

    # [blob & raw] file url
    if (($url -like "*/-/blob/*") -or ($url -like "*/-/raw/*")) {
        # get file info
        $url = ($url).replace("/-/blob/", "/-/raw/")
        $info = (($url).split("/-/raw")[1]).split("/") | Where-Object { $_ -ne '' }
        $ref = $info[0]
        $path = (($info | select-object -Skip 1) -join '/').replace('/', '%2F').replace('.', '%2E')

        # download file
        $downloadpath = "$download_dir/$($info | Select-Object -Last 1)"
        Invoke-RestMethod -WebSession $gitsession -Uri "$gitserver/api/v4/projects/$id/repository/files/$path/raw?ref=$ref" `
            -OutFile "$downloadpath" -verbose:$false
        if(test-path $downloadpath){
            Write-Output "$($info | Select-Object -Last 1) >> [$download_dir/$($info | Select-Object -Last 1)]"
        }
        else{
            Write-Error "Gitlab URL Doesn't Exist"
        }
    }

}