# TimelapseGenerator.ps1
# Generates a customizable timelapse
# 
# Changelog:
# v1.2 - Some bugfixes for running as scheduled task, month-handling, etc.
# v1.1 - A bit more dynamic, updated ffmpeg to newest available version, changed codec to x265, added parameter handling
# v1.0 - Initial concept
param ($Camera,$Style='Daily',[string]$Month)

Set-Location $PSScriptRoot

if (!$Camera) { $Camera = Read-Host "Enter camera you want to process" }

switch ($Style) {
    "Daily"     { $rate = "10"; break}
    "Monthly"   { $rate = "2"; break}
#    "Yearly"    { $rate = "2"; break}
    default {"Something else happened"; break}
 }

$TempProcessingDir = "C:\Temp\AutoTimelapse\" # Photos are copied here for temporary processing
$TimelapsePhotoSrc = "\\megabyte.home.zyrex.org\Vault\Vault\Upload\Webcam\Timelapse\" # Here lies all the photos
$CompletedTimelapseDir = "\\megabyte.home.zyrex.org\Mediavault\Privat\Timelapses\" # Final resting place for the video


# Get Last month
$MonthProcess = (Get-Date).AddMonths(-1)
$MonthProcess = $MonthProcess|Get-Date -Format MM

# Use passed parameter if it exists
if ($Month) {
    $MonthProcess = $Month
}

# Copy photos to correct folder
$photos = Get-ChildItem $TimelapsePhotoSrc

if ($style -eq "Monthly") {
    $Copyphotos = $photos | Where-Object {$_.name -Like "$($Camera)_????$($MonthProcess)??_12-00-??.jpg"}
}
elseif ($Style -eq "Daily") {
    $photos = $photos|Where-Object {$_.length -gt 120000} # Maybe do a check on the size, it will require tuning
    $Copyphotos = $photos | Where-Object {$_.name -Like "$($Camera)_????$($MonthProcess)*"}
}
#elseif ($Style -eq "Yearly") {
#    # Takes all previous monthlies and combines them to a yearly timelapse
#    $MonthlyTimelapses = Get-ChildItem $CompletedTimelapseDir | Where-Object {$_.Name -like "*.mkv"}
#    foreach ($file in $MonthlyTimelapses) {
#        ""
#    }
#}

$regex = '(?<filedate>\d{4}(?:\.|-|_)?\d{2}(?:\.|-|_)?\d{2})[^0-9]'
If($Copyphotos[1] -match $regex) {
    $date = $Matches['filedate'] -replace '(\.|-|_)',''
    $date = [datetime]::ParseExact($date,'yyyyMMdd',[cultureinfo]::InvariantCulture)
    $Year = Get-date $date -Format yyyy
}

foreach ($lapse in $Copyphotos) {
    Copy-Item $lapse.fullname $TempProcessingDir\
    }
# Rename photos
$i = 1
Get-ChildItem $TempProcessingDir | Sort-Object | ForEach-Object { Rename-Item $_.FullName -NewName ("$($Camera)_{0:D5}.jpg" -f $i++) }

# Make timelapse 
if ($Style -eq "Daily" -or $style -eq "Monthly") {
    & ".\ffmpeg.exe" -r $rate -i "$tempProcessingDir\$($Camera)_%05d.jpg" -s hd1080 -c:v libx265 -crf 28 $CompletedTimelapseDir\$Camera-$Style-$Year-$MonthProcess.mkv
}
elseif ($Style -eq "Yearly") {
    & ".\ffmpeg.exe" -f concat -safe 0 -i $MonthlyTimelapses -c copy YearlyTimelapse-$Camera.mkv
}

# Cleanup
Remove-Item $TempProcessingDir\* -Force