###Gitlab: controllo i commit recenti dei singoli progetti###

#Questo script passa in rassegna tutti i progetti esistenti sul gitlab aziendale e per ognuno verifica la presenza di commit recenti in una finestra di giorni specificata
#Poi invia le statistiche rilevate a zabbix per avere lo storico dei progetti con commit recenti

#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
$projectsFound = 0
#conteggio progetti con  commit negli ultimi giorni
$projectWithCommits = 0
#conteggio progetti senza commit negli ultimi giorni
$projectWithNoCommits = 0
#conteggio commits degli ultimi giorni
$recentCommits = 0
#ultimi giorni da considerare
$lastDays = 7
#data per conteggio commits degli ultimi giorni
$requestDate = (Get-Date).AddDays(-$lastDays).toString("yyyy-MM-dd")
#nome file di log
$logFile = "GitlabCommits.log"
#nome file di log old
$oldLogFile = "GitlabCommits.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 COMMITS" }
    1 { WriteLogOutput $logFile 0 "LOG ERRORI GITLAB COMMITS" }
    2 { WriteLogOutput $logFile 0 "LOG FULL GITLAB COMMITS" }
    3 { WriteLogOutput $logFile 0 "LOG AMPOLLOSO GITLAB COMMITS" }
}
WriteLogOutput $logFile 0 ""
WriteLogOutput $logFile 0 "Percorso log: $logFolder"
WriteLogOutput $logFile 0 ""
WriteLogOutput $logFile 0 "Inizio Esecuzione Script: $startTime"
WriteLogOutput $logFile 0 ""
WriteLogOutput $logFile 0 "RICERCA DA $requestDate | ULTIMI $lastDays GIORNI"

#ciclo principale for che cicla da 1 a N projectNumber
for ($projectCount = $startProj; $projectCount -le $endProj; $projectCount++) {
    $callUrl = "https://gitlab.steamware.net/api/v4/projects/" + $projectCount + "/repository/commits?per_page=100&since=" + $requestDate
    try {
        $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
        WriteLogOutput $logFile 1 ""
        WriteLogOutput $logFile 1 "--------------------"
        WriteLogOutput $logFile 1 "**PROGETTO $projectCount**"
        if ($parsedResponse.Count -eq 0 ) {
            $projectWithNoCommits++
        }
        else {
            $projectWithCommits++
            foreach ($item in $parsedResponse) {
                if ($item.web_url) {
                    WriteLogOutput $logFile 1 "Date: $($item.committed_date) - Web Url: $($item.web_url)"
                    $recentCommits++
                }
            }
        }
        $projectsFound++
    }
    #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

#percentuale di projectWithCommits sul totale
$projectWithCommitsPercentage = [math]::Round(($projectWithCommits / $projectsFound) * 100, 1)

#percentuale di projectWithNoCommits sul totale
$projectWithNoCommitsPercentage = [math]::Round(($projectWithNoCommits / $projectsFound) * 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.ProjectsFound -o $projectsFound
& "C:\Program Files\Zabbix Agent\zabbix_sender.exe" -z zabproxy.ufficio -s "W2022-IIS04" -k Gitlab.LastDaysCommits -o $lastDays
& "C:\Program Files\Zabbix Agent\zabbix_sender.exe" -z zabproxy.ufficio -s "W2022-IIS04" -k Gitlab.RecentCommits -o $recentCommits
& "C:\Program Files\Zabbix Agent\zabbix_sender.exe" -z zabproxy.ufficio -s "W2022-IIS04" -k Gitlab.ProjectWithCommits -o $projectWithCommits
& "C:\Program Files\Zabbix Agent\zabbix_sender.exe" -z zabproxy.ufficio -s "W2022-IIS04" -k Gitlab.ProjectWithNoCommits -o $projectWithNoCommits
& "C:\Program Files\Zabbix Agent\zabbix_sender.exe" -z zabproxy.ufficio -s "W2022-IIS04" -k Gitlab.ProjectWithCommitsPercentage -o $projectWithCommitsPercentage
& "C:\Program Files\Zabbix Agent\zabbix_sender.exe" -z zabproxy.ufficio -s "W2022-IIS04" -k Gitlab.ProjectWithNoCommitsPercentage -o $projectWithNoCommitsPercentage
& "C:\Program Files\Zabbix Agent\zabbix_sender.exe" -z zabproxy.ufficio -s "W2022-IIS04" -k Gitlab.CheckCommitsDuration -o $durataScript

#scrivo a video le statistiche
WriteLogOutput $logFile 0 ""
WriteLogOutput $logFile 0 "PROGETTI TOTALI: $projectsFound"
WriteLogOutput $logFile 0 "COMMITS TOTALI: $recentCommits"
WriteLogOutput $logFile 0 "PROGETTI CON COMMITS: $projectWithCommits ($projectWithCommitsPercentage%)"
WriteLogOutput $logFile 0 "PROGETTI SENZA COMMITS: $projectWithNoCommits ($projectWithNoCommitsPercentage%)"
WriteLogOutput $logFile 0 ""
WriteLogOutput $logFile 0 "Fine Esecuzione Script: $endTime"
WriteLogOutput $logFile 0 ""
WriteLogOutput $logFile 0 "Durata Esecuzione Script: $durataScript secondi"
WriteLogOutput $logFile 0 ""