##==============================================================================================
##                                                                                            ##
##                             Batch Merge Subtitles with MKVMerge                            ##
##                                          By Miles                                          ##
##                   Idea from Iain McCain : https://superuser.com/a/1249870                  ##
##                                                                                            ##
##==============================================================================================
##                                                                                            ##
## Utilisation et conditions :                                                                ##
## - Il faut que les .srt et les .mkv soient dans le même dossier.                            ##
## - Il faut que les sous-titres externes .SRT aient le même nom de fichier que les .MKV.     ##
## - Il faut paramétrer l'extension des fichiers de sous-titres pour que ces derniers         ##
##      reflètent la langue : eng, fre,...                                                    ##
## - Il faudra par ailleurs modifier le code langage dans AudioLang_X et SubTrackLang_1       ##
## Il est possible de :                                                                       ##
## - spécifier des dossiers sources et destinations identiques ou différents                  ##
## - spécifier un titre de piste (pour toutes)                                                ##
##                                                                                            ##
##==============================================================================================
##                                                                                            ##
##                                         Objectifs :                                        ##
##              Remuxer un MKV avec un SRT externe présent dans le même dossiers.             ##
##   Il faut que ce SRT ait le même nom que le MKV, avec comme extension .eng.srt ou .fr.srt  ##
##                               en fonction de la langue du ST.                              ##
##                                                                                            ##
##==============================================================================================

#Set MKVMerge.exe Path
$MKVMerge = 'H:\z_MKV\mkvtoolnix\mkvmerge.exe'

#Set Source and Target directories (Don't put an \ at the end)
$sourceDirectory = "D:\DOSSIER_SOURCE"
$destinationDirectory = "F:\DOSSIER_DESTINATION"

#If source and destination are the same folder, set this to True, Otherwise let it to "False"
$merged_SUFFIX_name = "False"

#Set Subtitle Extension (Don't add the . before the extension)
$SubExtension = 'eng.srt'
#$SecondSubExtension = "sub"

# Track 0 = video

# ================== AUDIO ==================
# Track 1 = Audio n°1
# Name and language of Audio Track n°1
$AudioTrackName_1 = "1:Français - AC3 5.1"
$AudioLang_1 = "1:fr"
$AudioTrack_1_default = "1:no"

# Track 2 = Audio n°2
# Name of Audio Track n°2
# $AudioTrackName_2 = "2:English - AC3 5.1"
# $AudioLang_2 = "2:en"
# $AudioTrack_2_default = "2:yes"

# ================== SUBTITLES ==================
# Track 0 : beacause it's a SRT file
# Name and language of Subtitle Track n°1 + Sync Value
$SubTrackName_1 = "0:ENG SDH - SRT"
$SubTrackLang_1 = "0:en"
$SubTrack_1_default = "3:yes"
$sub_charset_1 = "3:UTF-8"
#$SubSYNCvalue_1 = "0000"

# ================== OTHER SETTINGS ==================
# Define track order
$track_order = "0:0,0:2,0:1,0:6,0:3,0:4"
# Define subtitles track to keep
$subtitle_tracks = "3,4,6"

##==============================================================================================
##==============================================================================================

##==============================================================================================
##==============================================================================================

# Testing if the Not-Merged folder already exists : if yes, it will be renamed, else it will be created.
$Path_Folder_NotMerged = $sourceDirectory + "\Not-Merged"
If(!(test-path $Path_Folder_NotMerged)) {
    New-Item -ItemType "Directory" -Force -Path $Path_Folder_NotMerged -Verbose
} else {
    # Don't know what's the best... TO BE IMPROVED
    #Move-Item -Path $Path_Folder_NotMerged -Destination "$sourceDirectory\Not-Merged--backup" -Verbose
    #Move-Item -Path $Path_Folder_NotMerged -Destination "$sourceDirectory\Not-Merged--backup" -Verbose
}


#Process
$Subs = Get-ChildItem $sourceDirectory -Filter "*.$SubExtension" | ForEach-Object { $_.FullName } | Sort-Object
$Count = $Subs.count
Write-Host "$Count MKV's to be processed."

Foreach ($Sub in $Subs) {
    #Get File Name
    $FormatName = $Sub.ToString()
    #$Name = $FormatName.TrimEnd(".$SubExtension")
    $Name = $FormatName.Substring(0,$FormatName.Length-($SubExtension.Length+1))
    $MKV = $Name + '.mkv'
    #$OtherSub = $Name + '.' + $SecondSubExtension

    # Title for the video track
    $VideoTrackName = (Get-Item $MKV).Basename

    #Set Output File Name
    #$Output = $Name + '___MERGED' + '.mkv'
    If ($merged_SUFFIX_name -eq "True") {
        $Output = $destinationDirectory + "\" + $VideoTrackName + '___MERGED' + '.mkv'
    } elseif ($merged_SUFFIX_name -eq "False") {
        $Output = $destinationDirectory + "\" + $VideoTrackName + '.mkv'
    } else {
        write-host "Error in the value of the merged_SUFFIX_name variable. Current value = $merged_SUFFIX_name" -foreground "red"
        write-host "Should be set to True or False.`nScript is exiting now..." -foreground "white"
        Exit
    }

    #Execute
    & $MKVMerge --title "$VideoTrackName" --track-order "0:0,0:1,0:2,1:0" -o "$Output" --no-subtitles --language "0:en" --track-name "0:$VideoTrackName" --default-track "0:yes" --language "1:$AudioLang_1" --track-name "1:$AudioTrackName_1" --default-track "1:yes" --language "2:$AudioLang_2" --track-name "2:$AudioTrackName_2" --default-track "2:no" "$MKV" --language "0:$SubTrackLang_1" --track-name "0:$SubTrackName_1" --default-track "0:yes" --sync "0:$SubSYNCvalue_1" "$Sub"

    If (Test-Path $Output) {
        #Clean Up
        #Remove-Item $MKV
        #Remove-Item $Sub
        #Remove-Item $OtherSub
        # Move to folder Not-Merged, this folder's existence has already been tested, and the folder is created.
        Move-Item -Path $MKV -Destination $Path_Folder_NotMerged -Verbose
        Move-Item -Path $Sub -Destination $Path_Folder_NotMerged -Verbose

        # Renaming the output file is not necessary if the output filename doesn't have __MERGED in it
        #Rename-Item -Path $Output -NewName $MKV -Verbose

    } Else {
        write-host "File NON-EXISTANT - $Output" -foreground "red"
        "File NON-EXISTANT - $Output" | Out-File "$destinationDirectory\Errors.txt" -Append
    }
}