# ┌──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
# │ Powershell Script                                                                                                    │
# │                                                                                                                      │
# │ Objective : to keep up to 2 internal subtiles form a MKV and adding 1 or 2 external SRT.                             │
# │                                                                                                                      │
# │ Configure :                                                                                                          │
# │     - the Audio_ variables                                                                                           │
# │     - the ExtSubTrack_ variables                                                                                     │
# │     - All variables before the function Get-SubID                                                                    │
# │     - The Track ID in the function Get-SubID + the filename for those track ID                                       │
# └──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘


Clear-Host

# Set MKVMerge.exe Path
$MKVMerge = "`"H:\z_MKV\mkvtoolnix\mkvmerge.exe`""
# For the parameters to pass to MKVMerge executable, will be construct

$sourceDirectory_1 = "PATH_TO_SOURCE_1"
$destinationDirectory = "PATH_TO_DESTINATION"

# Remove dots before the season or the resolution ?
$remove_dots = $true
# If there is the year in the title, set it to $true
$set_year_with_brackets = $false
# $chain_to_search = ''
# $chain__to_replace = ''
$chain_to_search = '(.*) S(\d{2})E(\d{2}).(.*)'
$chain__to_replace = '$1 - S$2E$3 - $4--Custom'

# Move MKV1 (and SRT) to Not-Merged folder ? Set to $false or $true
$move_mkv1_after_merge = $true

# ================== AUDIO ================== Common for all videos
# Track 1 = Audio n°1
# Name and language of Audio Track n°1
$AudioTrackName_1 = "1:Japonais - AAC 2.0"
$AudioLang_1 = "1:ja"                      # en for english / fr for french / ja for japanese
$AudioTrack_1_default = "1:yes"
# Define track order. Do not modify it unless you changed the track number in this section
$track_order = "0:0,0:1"

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

# To keep or not internal subtitles
$keep_internal_Sub = $false
# NOTE : Internal SUB always came first in the track order !

# ===========================================
# ================== Internal SUB ? =========
$Internal_SUB_Number = 2    # Works only if $External_SUB = $true
                            # Max 2 Internal SRT is configured in the script.
                            # If set to 2, must be 2 SRT configured 
$SubTrackName_1 = "Français - SRT"
$SubTrackLang_1 = "fr"              # en for english / fr for french / jp for japanese
$SubTrack_1_default = "yes"
$sub_charset_1 = "UTF-8"

$SubTrackName_2 = "English SDH - SRT"
$SubTrackLang_2 = "en"              # en for english / fr for french / jp for japanese
$SubTrack_2_default = "no"
$sub_charset_2 = "UTF-8"

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


# ===========================================
# ================== External SUB ? =========
# Must have the same name as MKV1
$External_SUB = $true
$External_SUB_Number = 1    # Works only if $External_SUB = $true
                            # Max 2 External SRT is configured in the script.
                            # If set to 2, must be 2 SRT configured 
# Set Subtitle Extension (Don't add the . before the extension)
$SubExtension_1 = 'fre.srt'
$SubExtension_2 = 'fre.srt'

#### FILE 2 - SRT_1 - 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
$ExtSubTrackName_1 = "0:Français - SRT"
$ExtSubTrackLang_1 = "0:fr"
$ExtSubTrack_1_default = "0:yes"
$ExtSub_charset_1 = "0:UTF-8"

#### FILE 3 - SRT_2 - 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
$ExtSubTrackName_2 = "0:Français - SRT"
$ExtSubTrackLang_2 = "0:fr"
$ExtSubTrack_2_default = "0:no"
$ExtSub_charset_2 = "0:UTF-8"

# Define track order - DO NOT TOUCH
$track_order_EXT_sub = ""
if ( $External_SUB -eq $true ) {
    if ( $External_SUB_Number -eq 1 ) {
        $track_order_EXT_sub += ",1:0"
        if ( $External_SUB_Number -eq 2 ) {
            $track_order_EXT_sub += ",2:0"
        }
    }
}
# ===========================================

function Get-SubID {         # FOR INTERNAL SUB !
    param (                  # sub_1_id for 1st sub to keep
        $file_name           # sub_2_id for 2nd sub to keep
    )

    switch ($file_name)        
    {
        "FILE1"
        {
            $sub_1_id = "4"
            $sub_2_id = "5"
            break
        }
        "FILE2"
        {
            $sub_1_id = "5"
            $sub_2_id = "6"
            break
        }
        #Default state
        Default
        {
            Write-Host "This file is not set in the script : $file_name" -ForegroundColor "red"
            Write-Host "End of script..." -ForegroundColor "red"
            Exit
        }
    }

    return $sub_1_id, $sub_2_id
}

#Process
$MKV_1_List = Get-ChildItem $sourceDirectory_1 -Filter "*.mkv" | ForEach-Object { $_.FullName } | Sort-Object
$Count_1 = $MKV_1_List.count
Write-Host "$Count_1 MKV's to be processed in $sourceDirectory_1."

# Testing if the Done_Remerged folder already exists : if yes, it will be renamed, else it will be created.
$Path_Folder_NotMerged_1 = $sourceDirectory_1 + "\Done_Remerged"
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
}


# #########################
# Check if there is the same number of .srt files as .mkv files
if ( $External_SUB -eq $true ) {
    if ( $External_SUB_Number -ge 1 ) {     # If $NB_External_SUB >= 1 (include =1 and =2)
        $SRT_1_List = Get-ChildItem $sourceDirectory_1 -Filter "*.$SubExtension_1" | ForEach-Object { $_.FullName } | Sort-Object
        $Count_1_SRT = $SRT_1_List.count
        Write-Host "$Count_1_SRT SRT's ($SubExtension_1) to be processed in $sourceDirectory_1."
        if ($Count_1 -eq $Count_1_SRT) {
            Write-Host "There is the same number of MKV and SRT n°1 files ($SubExtension_1) in this folder. Let's continue."
        } else {
            Write-Host "The number of MKV and SRT n°1 files isn't the same. ABORT..." -foreground "red"
            Exit
        }
    }
    
    if ( $External_SUB_Number -eq 2 ) {     # Only if $External_SUB_Number = 2
        $SRT_2_List = Get-ChildItem $sourceDirectory_1 -Filter "*.$SubExtension_2" | ForEach-Object { $_.FullName } | Sort-Object
        $Count_2_SRT = $SRT_2_List.count
        Write-Host "$Count_2_SRT SRT's ($SubExtension_2) to be processed in $sourceDirectory_1."

        if ($Count_1 -eq $Count_2_SRT) {
            Write-Host "There is the same number of MKV and SRT n°2 files ($SubExtension_2) in this folder. Let's continue."
        } else {
            Write-Host "The number of MKV and SRT n°2 files ($SubExtension_2) isn't the same. ABORT..." -foreground "red"
            Exit
        }
    }
}
# #########################

$compteur = 1

Foreach ($MKV_1 in $MKV_1_List) {
  
    Write-Host "" -ForegroundColor "black" -BackgroundColor "white"
    Write-Host "Traitement du fichier n° $compteur / $Count_1..." -ForegroundColor "black" -BackgroundColor "white"
    Write-Host "" -ForegroundColor "black" -BackgroundColor "white"

    # Clear variables
    $MKVMerge_param_start = ""
    $MKVMerge_param_mkv1 = ""
    $MKVMerge_param_srt1 = ""
    $MKVMerge_param_srt2 = ""
    $MKVMerge_param_all = ""
    $MKVMerge_sub_param = ""
    $SRT_1_Name = ""
    $SRT_2_Name = ""
    $SRT_1 = ""
    $SRT_2 = ""

    $FormatName_1 = (Get-Item $MKV_1).Basename
    $MKV_1_name = $FormatName_1.ToString()

    # Title for the video track and for the destination file
    $VideoTrackName = $MKV_1_name
    if ( $set_year_with_brackets -eq $true ) {
        $VideoTrackName = $VideoTrackName -replace '(\d{4}(?=.*S\d{2}E\d{2}))', '($1)'
      }
    if ( $remove_dots -eq $true ) {
        $VideoTrackName = $VideoTrackName -replace '\.(?=.*S\d{2}E\d{2})', ' '
    }
    $VideoTrackName = $VideoTrackName -replace $chain_to_search, $chain__to_replace
    $VideoTrackName = "$VideoTrackName"
    Write-Host "`tThe Video Track Name will be : `r`n`t`t  $VideoTrackName" -ForegroundColor "green"
    
    $Output = "$destinationDirectory" + "\" + "$VideoTrackName" + ".mkv"
    

    # DO NOT TOUCH - Common for all files
    $MKVMerge_audio_param = "--language $AudioLang_1 --track-name `"$AudioTrackName_1`" --default-track $AudioTrack_1_default"

    if (( $keep_internal_Sub -eq $true ) -and ( $Internal_SUB_Number -ne 0 )) {  

        $sub_1_id, $sub_2_id = Get-SubID $MKV_1_name
        
        # Track 2 = Sub n°1 to keep
        # Name and language of Subtitle Track n°1 + Sync Value
        $SubTrackName_1 = $sub_1_id + ":$SubTrackName_1"
        $SubTrackLang_1 = $sub_1_id + ":$SubTrackLang_1"
        $SubTrack_1_default = $sub_1_id + ":$SubTrack_1_default"
        $sub_charset_1 = $sub_1_id + ":$sub_charset_1"
        # Define track order
        $track_order += ",0:" + $sub_1_id
        $subtitle_tracks = "$sub_1_id"
        $MKVMerge_sub_param = "--sub-charset $sub_charset_1 --language $SubTrackLang_1 --track-name `"$SubTrackName_1`" --default-track $SubTrack_1_default"

        if ( $Internal_SUB_Number -eq 2 ) {
            # Track 3 = Sub n°2 to keep
            # Name and language of Subtitle Track n°1 + Sync Value
            $SubTrackName_2 = $sub_2_id + ":$SubTrackName_2"
            $SubTrackLang_2 = $sub_2_id + ":$SubTrackLang_2"
            $SubTrack_2_default = $sub_2_id + ":$SubTrack_2_default"
            $sub_charset_2 = $sub_2_id + ":$sub_charset_2"
            # Define track order
            $track_order += ",0:" + $sub_2_id
            $subtitle_tracks += ",$sub_2_id"
            $MKVMerge_sub_param += " --sub-charset $sub_charset_2 --language $SubTrackLang_2 --track-name `"$SubTrackName_2`" --default-track $SubTrack_2_default"
        }
    }
    elseif (( $keep_internal_Sub -eq $true ) -and ( $Internal_SUB_Number -eq 0 )) {
        write-host "Problem with `$keep_internal_Sub=$keep_internal_Sub and `$Internal_SUB_Number=$Internal_SUB_Number.`nIf `$keep_internal_Sub=true, `$Internal_SUB_Number should have a value different from 0 !" -ForegroundColor "Red"
        exit
    }

    if ( ( $External_SUB_Number -ne 0 ) -and ( $External_SUB -eq $true ) ) {
        
        # First external SRT to include
        $SRT_1_Name = $MKV_1_name + ".$SubExtension_1"
        $SRT_1 = $sourceDirectory_1 + "\" + $SRT_1_name
        
        $track_order += $track_order_EXT_sub

        $MKVMerge_param_srt1 = "--sub-charset $Extsub_charset_1 --language $ExtSubTrackLang_1 --track-name `"$ExtSubTrackName_1`" --default-track $ExtSubTrack_1_default `"$SRT_1`""
        $MKVMerge_param_srt_all = "$MKVMerge_param_srt1"
        if ( $External_SUB_Number -eq 2 ) {
            # Second external SRT to include
            $SRT_2_Name = $MKV_1_name + ".$SubExtension_2"
            $SRT_2 = $sourceDirectory_1 + "\" + $SRT_2_name
            
            $MKVMerge_param_srt2 = "--sub-charset $Extsub_charset_2 --language $ExtSubTrackLang_2 --track-name `"$ExtSubTrackName_2`" --default-track $ExtSubTrack_2_default `"$SRT_2`""
            $MKVMerge_param_srt_all += " $MKVMerge_param_srt2"
        }

        if ( $keep_internal_Sub -eq $false ) {
            $MKVMerge_param_start = "--output `"$Output`" --title `"$VideoTrackName`" --track-order `"$track_order`" --no-subtitles --track-name `"0:$VideoTrackName`" --default-track 0:yes"
            $MKVMerge_param_mkv1 = "$MKVMerge_audio_param `"$MKV_1`""
            $MKVMerge_param_all = "$MKVMerge_param_start  $MKVMerge_param_mkv1 $MKVMerge_param_srt_all"
        }
        else {            
            $MKVMerge_param_start = "--output `"$Output`" --title `"$VideoTrackName`" --track-order `"$track_order`" --subtitle-tracks $subtitle_tracks --track-name `"0:$VideoTrackName`" --default-track 0:yes"
            $MKVMerge_param_mkv1 = "$MKVMerge_audio_param $MKVMerge_sub_param `"$MKV_1`""
            $MKVMerge_param_all = "$MKVMerge_param_start  $MKVMerge_param_mkv1 $MKVMerge_param_srt_all"
        }
    }
    elseif (( $External_SUB_Number -eq 0 ) -and ( $External_SUB -eq $true )) {
        write-host "Problem with `$External_SUB_Number=$External_SUB_Number and `$External_SUB=$External_SUB.`nIf `$External_SUB=true, `$External_SUB_Number should have a value different from 0 !" -ForegroundColor "Red"
        exit
    } 
    
    # To modify a SubTrackName after previous operation... :
    # if ( $MKV_1_name -eq "BLABLA" ) {
    #     $SubTrackName_2 = $sub_2_id + ":Français Québécois - SRT"
    # }
   
    # Write-Host "`$MKVMerge_param_start = $MKVMerge_param_start" -ForegroundColor "White"
    # Write-Host "`$MKVMerge_param_mkv1 = $MKVMerge_param_mkv1" -ForegroundColor "White"
    # Write-Host "`$MKVMerge_param_all = $MKVMerge_param_all" -ForegroundColor "White"

    # Last step to command construction
    $command = "& $MKVMerge $MKVMerge_param_all"
    # Launch begin...
    Invoke-Expression $command

    Write-Host "" -ForegroundColor "black" -BackgroundColor "white"
    Write-Host "Fin du traitement du fichier n° $compteur / $Count_1." -ForegroundColor "black" -BackgroundColor "white"
    Write-Host "" -ForegroundColor "black" -BackgroundColor "white"

    If (-Not (Test-Path $Output) ) {
        write-host "File NON-EXISTANT - $Output" -foreground "red"
        "File NON-EXISTANT - $Output" | Out-File "$destinationDirectory\Errors.txt" -Append
    }
    else {
        if ( $move_mkv1_after_merge -eq $true ) {
            Move-Item -Path $MKV_1 -Destination $Path_Folder_NotMerged_1 -Verbose
            if ( $NB_External_SUB -ne 0 ) {
                Move-Item -Path $SRT_1 -Destination $Path_Folder_NotMerged_1 -Verbose
                if ( $NB_External_SUB -eq 2 ) {
                    Move-Item -Path $SRT_2 -Destination $Path_Folder_NotMerged_2 -Verbose
                }
            }
        }
    }

    $compteur++
    

}