modules/runner/functions.psm1

function Invoke-GitURL {
    param(
        [ValidateNotNullOrEmpty()]        
        [System.String]$url,
        [ValidateNotNullOrEmpty()]        
        [System.String]$token,
        [System.String]$param
    )

    # config
    $local_path = "/git-runner/scripts/downloads"
    $gitlab = "https://gitlab.com"

    $out = [hashtable]@{ }
    ((' ' + $param) -split ' -', 3) | Where-Object { $_ -match '\S' } | ForEach-Object {
        $t = ($_).split(' ')
        $out += @{
            $t[0] = $t[1]
        }
    }

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

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

    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 "$gitlab/api/v4/projects/$id/repository/files/$path/raw?ref=$ref" `
            -OutFile "$($info | Select-Object -Last 1)" -Verbose:$false
        Write-Output "Git-Run: $($info | Select-Object -Last 1) >> [$($local_path.FullName)/$($info | Select-Object -Last 1)]"
        Write-Output " "
    }
    else {
        break
    }

    # Powershell
    $file = Get-ItemProperty "$($info | Select-Object -Last 1)"
    if (($file).extension -eq '.ps1') {
        #schmod +x "$newfile_path"
        if ($out) {
            $term = & "$($file.FullName)" @out
        } 
        else {
            $term = & "$($file.FullName)"
        }

        Write-Output "$term"
        exit $LASTEXITCODE
    } 
}

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"
        }
    }

}