###Gitlab: controllo lo stato dei JobArtifacts dei singoli progetti###

#Questo script passa in rassegna tutti i progetti esistenti sul gitlab aziendale e per ognuno verifica lo stato dei JobArtifacts, poi invia a zabbix le statistiche.
#Tendenzialmente ogni progetto dovrebbe avere 4 JobArtifacts abilitati: nembro, azzano, gitea, gogs

#importo file contenente configurazioni
. .\ApiGit\ApiGitResources\ApiScriptsConfig.ps1
#importo file contenente funzioni 
. .\ApiGit\ApiGitResources\ApiScriptsFunctions.ps1

#rilevo time per log inizio analisi
$startTime = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
# avvio stopwatch
$mainStopWatch = [system.diagnostics.stopwatch]::StartNew()
#contatore ciclo do while
$projectCount = 1
#numero massimo di progetti da analizzare
$projectNumber = 1
#conteggio progetti trovati
$existingProjects = 0
#conteggio job trovati
$jobFound = 0
#nome file di log
$logFile = "GitlabJobArtifacts.log"
#nome file di log old
$oldLogFile = "GitlabJobArtifacts.old"

#creazione folder di Log se non esiste
CheckLogFolder

#rotazione vecchio logFile da .log a .old se esiste
RotateOldLog

#scrivo intestazione e inizio analisi
WriteLogOutput $logFile 0 "--------------------"
Switch ($logLevel) {
    0 { WriteLogOutput $logFile 0 "LOG SINTETICO GITLAB Job Artifacts" }
    1 { WriteLogOutput $logFile 0 "LOG ERRORI GITLAB Job Artifacts" }
    2 { WriteLogOutput $logFile 0 "LOG FULL GITLAB Job Artifacts" }
    3 { WriteLogOutput $logFile 0 "LOG AMPOLLOSO GITLAB Job Artifacts" }
}
WriteLogOutput $logFile 0 ""
WriteLogOutput $logFile 0 "Percorso log: $logFolder"
WriteLogOutput $logFile 0 ""
WriteLogOutput $logFile 0 "Inizio Esecuzione Script: $startTime"

#ciclo principale do/while che cicla da 1 a N projectNumber
do {
    #chiamata api che restituisce informazioni sullo stato dei JobArtifacts
    $callUrl = "https://gitlab.steamware.net/api/v4/projects/" + $projectCount + "/jobs"
    WriteLogOutput $logFile 1 ""
    WriteLogOutput $logFile 1 "--------------------"
    WriteLogOutput $logFile 1 "**PROGETTO $projectCount**"
    try {
        #parsing della risposta api convertita da json
        $Response = Invoke-WebRequest -URI $callUrl -Headers $gitlabHead -ContentType "application/json" -UseBasicParsing
        $parsedResponse = $Response.Content | ConvertFrom-Json
        #scrivo il numero del progetto nel terminale e su file
        $deleteAllUrl = "https://gitlab.steamware.net/api/v4/projects/" + $projectCount + "/artifacts"
        $deleteAllResponse = Invoke-WebRequest -URI $deleteAllUrl -Method DELETE -Headers $gitlabHead -ContentType "application/json" -UseBasicParsing
        $parsedDeleteAllResponse = $deleteAllResponse.Content | ConvertFrom-Json

        #foreach ($item in $parsedResponse) {
        #    WriteLogOutput $logFile 1 "ID: $($item.id) | Creato il: $($item.created_at) | URL: $($item.web_url)"
        #    $projectJobFound++
        #    $jobFound++
            #compongo chiamata api per erase job
            #$eraseUrl = "https://gitlab.steamware.net/api/v4/projects/" + $projectCount + "/jobs/" + $item.id + "/erase"
            #$EraseResponse = Invoke-WebRequest -URI $eraseUrl -Method DELETE -Headers $gitlabHead -ContentType "application/json" -UseBasicParsing
            #$parsedEraseResponse = $EraseResponse.Content | ConvertFrom-Json
            #compongo chiamata api per delete all job artifacts in a project
        #    $deleteAllUrl = "https://gitlab.steamware.net/api/v4/projects/" + $projectCount + "/artifacts"
        #    $deleteAllResponse = Invoke-WebRequest -URI $deleteAllUrl -Method DELETE -Headers $gitlabHead -ContentType "application/json" -UseBasicParsing
        #    $parsedDeleteAllResponse = $deleteAllResponse.Content | ConvertFrom-Json
        #}
        #WriteLogOutput $logFile 1 "Job trovati per il progetto $($projectCount): $($projectJobFound)"
        #$projectJobFound = 0
        $existingProjects++
    }
    #scrivo se trovo un errore durante il try/catch
    catch {
        $parsedError = $_ | ConvertFrom-Json
        WriteLogOutput $logFile 3 $($parsedError.message)
    }
    $projectCount++
}
#fine ciclo principale
while ($projectCount -le $projectNumber)

# fermo stopwatch e calcolo durata script
$mainStopWatch.Stop()
$durataScript = $mainStopWatch.Elapsed.TotalSeconds

#rilevo time per log fine analisi
$endTime = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")

#invio a zabbix le metriche rilevate tramite zabbix_sender.exe
#WriteLogOutput $logFile 0 ""
#& "C:\Program Files\Zabbix Agent\zabbix_sender.exe" -z zabproxy.ufficio -s "W2022-IIS04" -k Gitlab.Projects -o $existingProjects
#& "C:\Program Files\Zabbix Agent\zabbix_sender.exe" -z zabproxy.ufficio -s "W2022-IIS04" -k Gitlab.TotalJobArtifacts -o $JobArtifactsCount
#& "C:\Program Files\Zabbix Agent\zabbix_sender.exe" -z zabproxy.ufficio -s "W2022-IIS04" -k Gitlab.SuccessJobArtifacts -o $JobArtifactsSuccessCount
#& "C:\Program Files\Zabbix Agent\zabbix_sender.exe" -z zabproxy.ufficio -s "W2022-IIS04" -k Gitlab.ErrorsJobArtifacts -o $JobArtifactsErrorsCount
#& "C:\Program Files\Zabbix Agent\zabbix_sender.exe" -z zabproxy.ufficio -s "W2022-IIS04" -k Gitlab.SuccessJobArtifactsPercent -o $JobArtifactsSuccessPercentage
#& "C:\Program Files\Zabbix Agent\zabbix_sender.exe" -z zabproxy.ufficio -s "W2022-IIS04" -k Gitlab.ErrorsJobArtifactsPercent -o $JobArtifactsErrorsPercentage
#& "C:\Program Files\Zabbix Agent\zabbix_sender.exe" -z zabproxy.ufficio -s "W2022-IIS04" -k Gitlab.CheckJobArtifactsDuration -o $durataScript

#scrivo a video le statistiche
WriteLogOutput $logFile 0 ""
WriteLogOutput $logFile 0 "PROGETTI ANALIZZATI: $existingProjects"
WriteLogOutput $logFile 0 "Job Artifacts TOTALI: $jobFound"
WriteLogOutput $logFile 0 ""
WriteLogOutput $logFile 0 "Fine Esecuzione Script: $endTime"
WriteLogOutput $logFile 0 ""
WriteLogOutput $logFile 0 "Durata Esecuzione Script: $durataScript secondi"
WriteLogOutput $logFile 0 ""