$ErrorActionPreference = 'SilentlyContinue'
#$CurseLatest = ((Get-ChildItem -Path 'C:\PortablePrograms\packwiz\').FullName | Sort-Object -Descending)[0]
#$PackPath = "C:\Users\Jzjad\Documents\PiTek\PiTek 3.0-3.5.1.zip"



$APIendpoint    = 'https://api.curseforge.com'
$APIkey         = '$2a$10$JImTmfu6axMXbi7vPRNZWesM86H83rda4Cs1D7MElzm24XaXBSqYK'
$modID          = '255109'


#What packwiz file do we want, defaults to latest/nightly
$PackWizUri     = 'https://nightly.link/packwiz/packwiz/workflows/go/main/Linux%2064-bit%20x86.zip'

$PackWizExe = "./packwiz"
$PackFile = "pack.toml"
$UpdateInfo = "updateinfo"


#Get system arch, not used as at this time microsoft does not make a arm64 version of mcr.microsoft.com/powershell, and im not bothering to build one.
# $arch = dpkg --print-architecture


#API Headers
$headers = @{
    'Accept'    = 'application/json'
    'x-api-key' = $APIkey
}

#Request the current version from the API & Download it
Function Get-CurrentVersion {
    $GetFiles = "/v1/mods/$modID/files?pageSize=1"
    $uri = "$APIendpoint$GetFiles"
    $Request = Invoke-RestMethod -Uri $uri -Method Get -Headers $headers
    $rData = $Request.data
    Invoke-WebRequest -Uri $rData.downloadUrl -OutFile $rData.fileName -UseBasicParsing
    Write-Output "Current Version: " + $rData
    return $rData.fileName
}
# https://edge.forgecdn.net/files/4312/606/PiTek 3.0-3.99.zip
Function Send-Version ($NewVer){
    #Uploader.py file, displayName, ChangeLog
    $file           = "PiTek 3.0-$NewVer.zip"
    $displayName    = $file | Split-Path -LeafBase
    if(Test-Path $file){
        try {
            Start-Process python3 -ArgumentList "Uploader.py -f `"$file`" -d `"$displayName`" -c `"$UpdateInfo`"" -NoNewWindow -Wait
            Write-Output "Pack maybe uploaded..."
        }
        catch {
            Write-Output "The following error occured while attempting to upload the pack"
            Write-Error -Message $_
            exit
        }
    }
    else {
        Write-Output "No file found at $file"
        exit
    }
}



function Update-Version {
    #Change version in toml file matching the regex as follows.
    #Get Current Version as well as assign new version
    $file = Get-Content "$PackFile"
    $pattern = "version\s=\s`"(.*?)`""
    $CurrentVersion = ([regex]::Match($file,$pattern).Groups[1].Value) -as [decimal]
    $NewVer = $CurrentVersion + 0.001
    (Get-Content "$PackFile") -Replace 'version\s=\s"[0-9].[0-9]{2,3}"', "version = `"$NewVer`"" | Set-Content "$PackFile"
    New-Changelog $NewVer
}

function Request-Update {
    #Clear the previous update output
    Clear-Content $UpdateInfo -Force

    #Have Packwiz check for updates
    Start-Process -FilePath $PackWizExe -ArgumentList "update --all --yes --pack-file $PackFile" -NoNewWindow -Wait -RedirectStandardOutput $UpdateInfo

    $Result = Get-Content $UpdateInfo
    if ($Result -match 'All files are up to date!'){
        Write-Output "No mods to update, exiting"
        exit
    }
    elseif (($Result -match 'Files updated') -and ($Result -match 'Updates found')) {
        Write-Output "Mods where updated proceeding"
        Update-Version
    }
    else {
        Write-Output "What the fuck, nothing matched?"
    }
}


Function Get-PackWiz($Uri) {
    try {
        Invoke-WebRequest -Uri $Uri -OutFile "packwiz.zip" -UseBasicParsing
        Expand-Archive "packwiz.zip" -DestinationPath $PWD -Force
        Start-Process chmod -ArgumentList "+x $PackWizExe" -NoNewWindow -Wait
    }
    catch {
        Write-Output "The following error occured wwhile attempting to fetch Packwiz"
        Write-Output $_
        exit
    }
}


Function Import-CurrentPack($CurrentVer) {
    try {
        Start-Process -FilePath $PackWizExe -ArgumentList "curseforge import `"$CurrentVer`" -y" -NoNewWindow -Wait
        Request-Update
    }
    catch {
        Write-Output "The following error occured while attempting to import the pack"
        Write-Output $_
        exit
    }
}

Function Export-NewPack($NewVer) {
    try {
        Start-Process -FilePath $PackWizExe -ArgumentList "curseforge export" -NoNewWindow -Wait
        Send-Version $NewVer
    }
    catch {
        Write-Output $_
    }
}

Function New-Changelog ($NewVer) {
    #Get a list of the updated mods
    $UpdatedMods = (Get-Content $UpdateInfo | Select-Object -Skip 4 | Select-Object -SkipLast 2) -replace '.jar',''

    #Clean content of possible existing files
    Clear-Content -Path "$UpdateInfo.html" -Force
    Clear-Content -Path "$UpdateInfo.md" -Force

    #Now we create the update file in html for curse.
    Add-Content -Path "$UpdateInfo.html" -Value "Updated Mods`n`n<hr />`n`n`n<ul>" -Force
    Add-Content -Path "$UpdateInfo.html" -Value $($UpdatedMods | ForEach-Object {"<li>" + $_ + "</li>"}) -Force
    Add-Content -Path "$UpdateInfo.html" -Value "</ul>" -Force
    Get-Content -Path "$UpdateInfo.html" | Write-Output

    #Now we create the update file in MD for the discord webhook.
    $Counter=0

    Add-Content -Path "$UpdateInfo.md" -Value "**Updated Mods**" -Force
    Add-Content -Path "$UpdateInfo.md" -Value '```md' -Force
    Add-Content -Path "$UpdateInfo.md" -Value $($UpdatedMods | ForEach-Object {$Counter = $Counter + 1; "$Counter. " + $_}) -Force
    Add-Content -Path "$UpdateInfo.md" -Value '```' -Force
    Get-Content -Path "$UpdateInfo.md" | Write-Output


    Export-NewPack $NewVer
}


$CurrentVersion = Get-CurrentVersion




#We start the script here

Get-PackWiz $PackWizUri
Import-CurrentPack $CurrentVersion

