##==============================================================================================
##                                                                                            ##
##                             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 deux MKV en gardant l'audio et les chapitres du premier, et seulement la vidéo  ##
## du second, en muxant en plus un SRT ayant le même nom que le 1er mkv et étant dans le même ##
##                                   dossier que ce 1er mkv                                   ##
##                                                                                            ##
##==============================================================================================


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

#Set Source and Target directories (Don't put an \ at the end)
$sourceDirectory_1 = "D:\DOSSIER_SOURCE-1"
$sourceDirectory_2 = "D:\DOSSIER_SOURCE-2"
$destinationDirectory = "G:\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'

#### Objective : Keep audio and subtitles and tags from FILE n°1 - Add video from FILE n°2

##########################################
#### FILE 1 - MKV - Keeping all but the video (audio + chapters tags)
# ================== AUDIO ==================
# Track 1 = Audio n°1
# Name and language of Audio Track n°1
$AudioTrackName_1 = "1:English - DTS 5.1 768kb/s"
$AudioLang_1 = "1:fr"
$AudioTrack_1_default = "1:yes"
$file_1_options = "--no-video"

##########################################
#### FILE 2 - MKV - Keeping only the video
$file_2_options = "--no-audio --no-track-tags --no-global-tags"

##########################################
#### FILE 3 - SRT - Keeping all but the video (audio + chapters tags)
# ================== SUBTITLES ==================
# Track 0 = Sub n°1 to keep
# Name and language of Subtitle Track n°0 + Sync Value
$SubTrackName_1 = "0:English SDH - SRT"
$SubTrackLang_1 = "0:en"
$SubTrack_1_default = "0:yes"
$sub_charset_1 = "0:UTF-8"
####

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

# Files name, without .mkv : 
#       format = filename_1_part_1 + S + filename_season + E + i_counter + filename_1_part_2 + .mkv
#       format = filename_2_part_1 + S + filename_season + E + i_counter + filename_2_part_2 + .mkv
$filename_1_part_1 = "Ma série (20xx) - "
$filename_1_part_2 = " - 1080p-h264"
# Final name 1 = Ma série (20xx) - S01E01 - 1080p-h264
# The SRT file must have the same name (without the extention .eng.srt) 

$filename_2_part_1 = "Ma série (20xx) - "
$filename_2_part_2 = " - 1080p.x265"
# Final name 2 = Ma série (20xx) - S01E01 - 1080p.x265

$filename_season = "01"
$filename_ep_start = 4
$filename_ep_final = 4
##==============================================================================================
##==============================================================================================

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

#Process
$MKV_1_List = Get-ChildItem $sourceDirectory_1 -Filter "*.mkv" | ForEach-Object { $_.FullName } | Sort-Object
$SRT_1_List = Get-ChildItem $sourceDirectory_1 -Filter "*.$SubExtension" | ForEach-Object { $_.FullName } | Sort-Object
$Count_1 = $MKV_1_List.count
$Count_1_SRT = $SRT_1_List.count
Write-Host "$Count_1 MKV's to be processed and $Count_1_SRT SRT's to be processed in $sourceDirectory_1."
if ($Count_1 -eq $Count_1_SRT) {
    Write-Host "There is the same number of MKV and SRT file in this folder. Let's continue."
} else {
    Write-Host "The number of MKV and SRT files isn't the same. ABORT..." -foreground "red"
    Exit
}

$MKV_2_List = Get-ChildItem $sourceDirectory_2 -Filter "*.mkv" | ForEach-Object { $_.FullName } | Sort-Object
$Count_2 = $MKV_2_List.count
Write-Host "$Count_2 MKV's to be processed in $sourceDirectory_2."
if ($Count_1 -eq $Count_2) {
    Write-Host "There is the same number of MKV in the two sources folders. Let's continue."
} else {
    Write-Host "The number of MKV in the two sources folders isn't the same. ABORT..." -foreground "red"
    Exit
}

if (!($Count_1 -eq ($filename_ep_final - $filename_ep_start + 1))) {
    Write-Host "The number of epidoes set in the script isn't the same as the number of files in the folders... EXITING NOW !" -foreground "red"
    Exit
}

for ($i = $filename_ep_start; $i -lt $filename_ep_final+1; $i++) {
    
    # Genreating File Name
    #       format = filename_1_part_1 + S + filename_season + E + i_counter + filename_1_part_2 + .mkv
    #       format = filename_2_part_1 + S + filename_season + E + i_counter + filename_2_part_2 + .mkv
    # Final name 1 = Le Bureau des Légendes (2015) - S01E01 - 1080p-h264
    # Final name 2 = Le Bureau des Légendes (2015) - S01E01 - 1080p.BDRip.x265.Aac.NoTag

    if ($i -lt 10 ) { # i<10
        $MKV_1_name = $filename_1_part_1 + "S" + $filename_season + "E0" + $i + $filename_1_part_2
        $SRT_1_name = $MKV_1_name
        $MKV_2_name = $filename_2_part_1 + "S" + $filename_season + "E0" + $i + $filename_2_part_2
    } else {    # i=10
        $MKV_1_name = $filename_1_part_1 + "S" + $filename_season + "E" + $i + $filename_1_part_2
        $SRT_1_name = $MKV_1_name
        $MKV_2_name = $filename_2_part_1 + "S" + $filename_season + "E" + $i + $filename_2_part_2
    }
    $MKV_1 = $sourceDirectory_1 + "\" + $MKV_1_name + ".mkv"
    $SRT_1 = $sourceDirectory_1 + "\" + $SRT_1_name + "." + $SubExtension
    $MKV_2 = $sourceDirectory_2 + "\" + $MKV_2_name + ".mkv"

    # Title for the video track
    $VideoTrackName = $MKV_2_name

    #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
    # Keep Audio/Subtitles/tags from MKV_1 + Only video from MKV_2
<# Command to edit
& $MKVMerge --title "$VideoTrackName" --track-order "$track_order" -o "$Output"
"$file_1_options" 
--language "$AudioLang_1" --track-name "$AudioTrackName_1" --default-track "$AudioTrack_1_default" 
"$MKV_1"
"$file_2_options"
--language "0:en" --track-name "0:$VideoTrackName" --default-track "0:yes"
"$MKV_2"
--sub-charset "$sub_charset_1" --language "$SubTrackLang_1" --track-name "$SubTrackName_1" --default-track "$SubTrack_1_default"
"$SRT_1"
#>
    
    & $MKVMerge --title "$VideoTrackName" --track-order "$track_order" -o "$Output" --no-video --language "$AudioLang_1" --track-name "$AudioTrackName_1" --default-track "$AudioTrack_1_default" "$MKV_1" --no-audio --no-track-tags --no-global-tags --language "0:en" --track-name "0:$VideoTrackName" --default-track "0:yes" "$MKV_2" --sub-charset "$sub_charset_1" --language "$SubTrackLang_1" --track-name "$SubTrackName_1" --default-track "$SubTrack_1_default" "$SRT_1"

    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_1 -Destination $Path_Folder_NotMerged_1 -Verbose
        Move-Item -Path $SRT_1 -Destination $Path_Folder_NotMerged_1 -Verbose
        Move-Item -Path $MKV_2 -Destination $Path_Folder_NotMerged_2 -Verbose
        #Move-Item -Path $Sub -Destination $Path_Folder_NotMerged_2 -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
    }
}