#!/usr/bin/env bash

source ./secrets.sh

# Function to URL encode a string
urlencode() {
    local string="$1"
    local encoded=""
    local char

    for (( i=0; i<${#string}; i++ )); do
        char="${string:i:1}"
        case "$char" in
            [a-zA-Z0-9.~_-]) encoded+="$char" ;;
            " ") encoded+="%20" ;;
            *) encoded+=$(printf '%%%02X' "'$char") ;;
        esac
    done
    echo "$encoded"
}

# Use mediainfo to get HDR type of video
# 0=NoHDR, 1=HDR10, 2=DolbyVision
getHDRType() {
    local movie_path="$1"

    case $(mediainfo --Output=JSON "$movie_path" | ./jq -r '[.media.track[] | select(.["@type"] == "Video")] | .[0].HDR_Format' ) in
        *"Dolby Vision"*) echo "2" ;;
        "null") echo "0" ;;
        *) echo "1" ;;
    esac
}

encodeDV() {
    local local_title="$1"

    HandBrakeCLI -i "../$local_title/$local_title - 4k DV.mkv" -o "../$local_title/temp/handbrake.mkv" -f av_mkv -m -e x265_10bit --encoder-preset slower -q 20 --encoder-profile auto --all-audio -E copy --audio-copy-mask aac,eac3,dts,ac3,truehd,dtshd,mp3 --crop-mode auto --auto-anamorphic --all-subtitles

    ffmpeg -i "../$local_title/$local_title - 4k DV.mkv" -c:v copy -f hevc - | ./dovi_tool -m 2 --crop extract-rpu - -o "../$local_title/temp/rpu.bin"

    ffmpeg -i "../$local_title/temp/handbrake.mkv" -c:v copy "../$local_title/temp/nonhdr.hevc"

    ./dovi_tool inject-rpu -i "../$local_title/temp/nonhdr.hevc" --rpu-in "../$local_title/temp/rpu.bin" -o "../$local_title/temp/hdrcompressed.hevc"

    mkvmerge --output "../$local_title/$local_title/$local_title - 4k DVP8 Subs.mkv" "../$local_title/temp/hdrcompressed.hevc" -D -S -B -T --no-chapters -M --no-global-tags "../$local_title/temp/handbrake.mkv" --default-track-flag 0:no --language 0:en "../$local_title/$local_title.en.srt" -D -A "../$local_title/temp/handbrake.mkv"
}

encodeHDR() {
    local local_title="$1"

    HandBrakeCLI -i "../$local_title/$local_title - 4k.mkv" -o "../$local_title/temp/handbrake.mkv" -f av_mkv -m -e x265_10bit --encoder-preset slower -q 20 --encoder-profile auto --all-audio -E copy --audio-copy-mask aac,eac3,dts,ac3,truehd,dtshd,mp3 --crop-mode auto --auto-anamorphic --all-subtitles

    mkvmerge --output "../$local_title/$local_title/$local_title - 4k Subs.mkv" -S --no-chapters "../$local_title/temp/handbrake.mkv" --default-track-flag 0:no --language 0:en "../$local_title/$local_title.en.srt" -A -D -B -T -M --no-global-tags "../$local_title/temp/handbrake.mkv"
}

encodeNonHDR() {
    local local_title="$1"

    HandBrakeCLI -i "../$local_title/$local_title.mkv" -o "../$local_title/$local_title/$local_title.mkv" -f av_mkv -m -e x265 --encoder-preset slower -q 20 --encoder-profile auto --all-audio -E copy --audio-copy-mask aac,eac3,dts,ac3,truehd,dtshd,mp3 --crop-mode auto --auto-anamorphic --all-subtitles
}


counter=1
folders=()
for dir in ../*/; do
    folder_name="${dir#../}"
    folder_name="${folder_name%/}"
    echo "$counter. $folder_name"
    folders+=("$folder_name")
    counter=$((counter + 1))
done

read -r -p "Please select a folder by entering the corresponding number: " selection

#Assuming folder name is name of movie
title="${folders[$((selection - 1))]}"
folder_path="../$title/"
echo "You selected: $title"

# URL encode the movie title
encoded_title=$(echo "$title" | sed -E 's/ \([0-9]{4}\)$//')
encoded_title=$(urlencode "$encoded_title")

# Search The Movie Database
json_results=$(curl -s --request GET \
     --url "https://api.themoviedb.org/3/search/movie?query=$encoded_title&include_adult=false&language=en-US&page=1" \
     --header "Authorization: Bearer $themoviedb_token" \
     --header 'accept: application/json' | ./jq)

# Show first results and have user select right result
echo "Select the correct movie title:"
echo "$json_results" | ./jq -r '.results[:3] | to_entries[] | "\(.key + 1). \(.value.title) (\(.value.release_date))"'
read -r -p "Selection: " selection

# Get the selected movie details
selected_movie=$(echo "$json_results" | ./jq -r ".results[$((selection - 1))]")

full_title=$(echo "$selected_movie" | ./jq -r '. | "\(.original_title) (\(.release_date | split("-")[0]))"')

if [[ "../$full_title/" != "$folder_path" ]]; then
    echo "Updating folder name to \"$full_title\""
    mv "$folder_path" "../$full_title"
fi

#Find mkv files in folder
for movie in "../$full_title/"*.mkv; do
    echo "Found mkv file $movie"
done

hdr_type=$(getHDRType "$movie")

mkdir "../$full_title/temp"
mkdir "../$full_title/$full_title"

case "$hdr_type" in
    2) {
        mv "$movie" "../$full_title/$full_title - 4k DV.mkv"
        encodeDV "$full_title"
    };;
    1) {
        mv "$movie" "../$full_title/$full_title - 4k.mkv"
        encodeHDR "$full_title"
    };;
    0) {
        mv "$movie" "../$full_title/$full_title.mkv"
        encodeNonHDR "$full_title"
    };;
esac

poster_path="https://image.tmdb.org/t/p/original$(echo "$selected_movie" | ./jq -r '.poster_path')"
echo "Downloading Poster..."
curl -s -o "../$full_title/$full_title/poster.${poster_path##*.}" "$poster_path"

echo "$full_title encode complete."


