###Gitlab_Azzano: controllo lo stato delle pipeline dei singoli progetti###

#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
$startProj = 1
#numero massimo di progetti da analizzare
$endProj = 250
#conteggio progetti trovati
$projectsWithPipeline = 0
#conteggio pipeline in errore
$pipelineErrorsCount = 0
#conteggio pipeline riusciti
$pipelineSuccessCount = 0
#nome file di log
$logFile = "GitlabAzzanoPipeline.log"
#nome file di log old
$oldLogFile = "GitlabAzzanoPipeline.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 AZZANO PIPELINE" }
    1 { WriteLogOutput $logFile 0 "LOG ERRORI GITLAB AZZANO PIPELINE" }
    2 { WriteLogOutput $logFile 0 "LOG FULL GITLAB AZZANO PIPELINE" }
    3 { WriteLogOutput $logFile 0 "LOG AMPOLLOSO GITLAB AZZANO PIPELINE" }
}
WriteLogOutput $logFile 0 ""
WriteLogOutput $logFile 0 "Percorso log: $logFolder"
WriteLogOutput $logFile 0 ""
WriteLogOutput $logFile 0 "Inizio Esecuzione Script: $startTime"

#ciclo principale for che cicla da startProj a endProj
for ($projectCount = $startProj; $projectCount -le $endProj; $projectCount++){
    $callUrl = "https://gitlab-azzano.steamware.net/api/v4/projects/" + $projectCount + "/pipelines/latest"
    try {
        $Response = Invoke-WebRequest -URI $callUrl -Headers $azzanoHead -ContentType "application/json" -UseBasicParsing
        $parsedResponse = $Response.Content | ConvertFrom-Json
        #scrivo il numero del progetto nel terminale e su file
        WriteLogOutput $logFile 1 ""
        WriteLogOutput $logFile 1 "--------------------"
        WriteLogOutput $logFile 1 "**PROGETTO $projectCount**"
        foreach ($item in $parsedResponse) {
            #verifico se i pipeline trovati per il progetto corrente hanno status "success"
            if ($item.status.Equals("success")) {
                WriteLogOutput $logFile 2 "Pipeline: $($item.web_url) - Status: $($item.status)"
                $pipelineSuccessCount++
            }
            #i pipeline che non hanno status "success" vengono loggati con relativo errore
            else {
                WriteLogOutput $logFile 1 "Pipeline: $($item.web_url) - Status: $($item.status)"
                $pipelineErrorsCount++
            }
        }
        $projectsWithPipeline++
    }
    #scrivo se trovo un errore durante il try/catch
    catch {
        $parsedError = $_ | ConvertFrom-Json
        WriteLogOutput $logFile 3 ""
        WriteLogOutput $logFile 3 "--------------------"
        WriteLogOutput $logFile 3 "**ERRORE NEL PROGETTO $projectCount**"
        WriteLogOutput $logFile 3 $($parsedError.message)
    }
}
#fine ciclo principale

#somma di pipelineSuccess e pipelineErrors
$pipelineCount = $pipelineSuccessCount + $pipelineErrorsCount

#percentuale di pipelineSuccess sul totale
$pipelineSuccessPercentage = [math]::Round(($pipelineSuccessCount / $pipelineCount) * 100, 1)

#percentuale di pipelineErrors sul totale
$pipelineErrorsPercentage = [math]::Round(($pipelineErrorsCount / $pipelineCount) * 100, 1)

# 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.ProjectsWithPipeline -o $projectsWithPipeline
#& "C:\Program Files\Zabbix Agent\zabbix_sender.exe" -z zabproxy.ufficio -s "W2022-IIS04" -k Gitlab.TotalPipeline -o $pipelineCount
#& "C:\Program Files\Zabbix Agent\zabbix_sender.exe" -z zabproxy.ufficio -s "W2022-IIS04" -k Gitlab.SuccessPipeline -o $pipelineSuccessCount
#& "C:\Program Files\Zabbix Agent\zabbix_sender.exe" -z zabproxy.ufficio -s "W2022-IIS04" -k Gitlab.ErrorsPipeline -o $pipelineErrorsCount
#& "C:\Program Files\Zabbix Agent\zabbix_sender.exe" -z zabproxy.ufficio -s "W2022-IIS04" -k Gitlab.SuccessPipelinePercent -o $pipelineSuccessPercentage
#& "C:\Program Files\Zabbix Agent\zabbix_sender.exe" -z zabproxy.ufficio -s "W2022-IIS04" -k Gitlab.ErrorsPipelinePercent -o $pipelineErrorsPercentage
#& "C:\Program Files\Zabbix Agent\zabbix_sender.exe" -z zabproxy.ufficio -s "W2022-IIS04" -k Gitlab.CheckPipelineDuration -o $durataScript

#scrivo a video le statistiche
WriteLogOutput $logFile 0 ""
WriteLogOutput $logFile 0 "PROGETTI CON PIPELINE ATTIVE: $projectsWithPipeline"
WriteLogOutput $logFile 0 "PIPELINE TROVATE: $pipelineCount"
WriteLogOutput $logFile 0 "PIPELINE RIUSCITE: $pipelineSuccessCount ($pipelineSuccessPercentage%)"
WriteLogOutput $logFile 0 "PIPELINE FALLITE: $pipelineErrorsCount ($pipelineErrorsPercentage%)"
WriteLogOutput $logFile 0 ""
WriteLogOutput $logFile 0 "Fine Esecuzione Script: $endTime"
WriteLogOutput $logFile 0 ""
WriteLogOutput $logFile 0 "Durata Esecuzione Script: $durataScript secondi"
WriteLogOutput $logFile 0 ""