##==============================================================================================
##                                                                                            ##
##                             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 en ne gardant que 3 pistes de sous-titres SRT et les 2 pistes audio     ##
##   en spécifiant un nom pour chaque piste et en permettant de paramétrer celles par défaut  ##
##                                 ainsi que l'odre des pistes                                ##
##                   Le MKV de base contient 3 pistes SRT. On en garde que 3.                 ##
##                                                                                            ##
##==============================================================================================

#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\3ST"
$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 3 = Sub n°1 to keep
# Name and language of Subtitle Track n°1 + Sync Value
$SubTrackName_1 = "3:FR Forcé - SRT"
$SubTrackLang_1 = "3:fr"
$SubTrack_1_default = "3:no"
$sub_charset_1 = "3:UTF-8"

# Track 4 = Sub n°2 to keep
# Name and language of Subtitle Track n°2 + Sync Value
$SubTrackName_2 = "4:FR Complet - SRT"
$SubTrackLang_2 = "4:fr"
$SubTrack_2_default = "4:no"
$sub_charset_2 = "4:UTF-8"

# Track 5 = Sub n°3 to keep
# Name and language of Subtitle Track n°3 + Sync Value
$SubTrackName_3 = "5:ENG Full - SRT"
$SubTrackLang_3 = "5:en"
$SubTrack_3_default = "5:yes"
$sub_charset_3 = "5:UTF-8"

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

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

# 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 - Grab the list of all MKV file in the folder
$MKV_List = Get-ChildItem $sourceDirectory -Filter "*.mkv" | ForEach-Object { $_.FullName } | Sort-Object
$Count = $MKV_List.count
Write-Host "$Count MKV's to be processed in $sourceDirectory."

Foreach ($MKV_file in $MKV_List) {
    #Get File Name
    $FormatName = $MKV_file.ToString()
    $Name = $FormatName.Substring(0,$FormatName.Length-(4))
    $MKV = $FormatName
    #$OtherSub = $Name + '.' + $SecondSubExtension

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

    #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 : Merge SRT with MKV
    #& $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"

    # Delete PGS subtitles in MKV keeping all the rest
#    & $MKVMerge --title "$VideoTrackName" --track-order "$track_order" -o "$Output" --subtitle-tracks "$subtitle_tracks" --language "0:en" --track-name "0:$VideoTrackName" --default-track "0:yes" 
#    --language "$AudioLang_1" --track-name "$AudioTrackName_1" --default-track "$AudioTrack_1_default"
#    --language "$AudioLang_2" --track-name "$AudioTrackName_2" --default-track "$AudioTrack_2_default"
#    --sub-charset "$sub_charset_1" --language "$SubTrackLang_1" --track-name "$SubTrackName_1" --default-track "$SubTrack_1_default"
#    --sub-charset "$sub_charset_2" --language "$SubTrackLang_2" --track-name "$SubTrackName_2" --default-track "$SubTrack_2_default"
#    --sub-charset "$sub_charset_3" --language "$SubTrackLang_3" --track-name "$SubTrackName_3" --default-track "$SubTrack_3_default"
#    "$MKV"
    & $MKVMerge --title "$VideoTrackName" --track-order "$track_order" -o "$Output" --subtitle-tracks "$subtitle_tracks" --language "0:en" --track-name "0:$VideoTrackName" --default-track "0:yes" --language "$AudioLang_1" --track-name "$AudioTrackName_1" --default-track "$AudioTrack_1_default" --language "$AudioLang_2" --track-name "$AudioTrackName_2" --default-track "$AudioTrack_2_default" --sub-charset "$sub_charset_1" --language "$SubTrackLang_1" --track-name "$SubTrackName_1" --default-track "$SubTrack_1_default" --sub-charset "$sub_charset_2" --language "$SubTrackLang_2" --track-name "$SubTrackName_2" --default-track "$SubTrack_2_default" --sub-charset "$sub_charset_3" --language "$SubTrackLang_3" --track-name "$SubTrackName_3" --default-track "$SubTrack_3_default" "$MKV"

    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
    }
}