#SCRIPT PER ROBOCOPIARE CARTELLA WEBDOOR

####INIZIO DICHIARAZIONE VARIABILI####

# num gg per cui tenere i log
$Days = "30"
$CutoffDate = (Get-Date).AddDays(-$Days)

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

# avvio stopwatch
$mainStopWatch = [system.diagnostics.stopwatch]::StartNew()

#abilitazione log: 0=disattivo, 1=abilitato
$logEnable = 0

#cartella file di log
$WdcLogFolder = "c:\Steamware\Logs\WDC\"

#nome file di log
$dayName = "WDC_" + (Get-Date).toString("yyyy-MM-dd") + ".log"
$logFile = Join-Path $WdcLogFolder $dayName

#folder source per robocopy
$sourceFolder = "U:\NextCloud\ABH\Compo" 

#folder destination per robocopy
$destFolder = "U:\WebDoorSync\NewComp\Compo"

# ex W2022-IIS04
#$sourceFolder = "\\stor01\TEAM DRIVES\30_Clienti\ABH\DataImport\Compo" 
#$destFolder = "\\W2022-IIS04\WebDoorSync\NewComp\Compo"

####FINE DICHIARAZIONE VARIABILI####

#dichiaro funzione per scrittura output
Function WriteLogOutput {
    Param ([string]$logString)
    #scrivo su file la stringa
    Add-content $logFile -value "$logString"
    #scrivo su terminale la stringa se $logEnable=1
    if ($logEnable -eq 1) {
        Write-Output($logString)
    }
}

#creazione folder di Log se non già esistente
if (Test-Path $WdcLogFolder) {
}
else {
    New-Item $WdcLogFolder -ItemType Directory
}

#effettuo robocopy
try {
    WriteLogOutput "------WDC SYNC------"
    if ($logEnable -eq 1) {
        robocopy $sourceFolder $destFolder /mir /log+:$logFile
    }
    else {
        WriteLogOutput ""
        WriteLogOutput "Started: $startTime"
        WriteLogOutput "Source: $sourceFolder"
        WriteLogOutput "Destination: $destFolder"
        robocopy $sourceFolder $destFolder /mir
    }
    WriteLogOutput "Robocopy OK"
}
catch {
    WriteLogOutput "An error occurred"
}

# elimino file log troppo vecchi
Get-ChildItem -Path $WdcLogFolder -Recurse -File | Where-Object { $_.LastWriteTime -lt $CutoffDate } | Remove-Item -Force
WriteLogOutput "Log Cleanup complete!"

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

#scrivo le statistiche
WriteLogOutput "Duration: $durataScript seconds"
WriteLogOutput ""
