#!/bin/bash

set -eu
set -o pipefail

source="/dev/sr1"

function usage
{
    retval="$1"
    case "$retval" in
        0)
            ;;
        *)
            exec 1>&2
            ;;
    esac
    echo "Usage: $0 --source $source --name moviename --help"
    exit "$retval"
}

while [ "$#" -ge 1 ]
do
    case "$1" in
        --source)
            source="$2"
            shift
            ;;
        --name)
            name="$2"
            shift
            ;;
        --help|-h)
            usage 0
            ;;
        *)
            echo "$0: Unrecognized option: $1" 1>&2
            usage 1
            ;;
    esac
    shift
done

# Find the base directory
basedir=""
for directory in /mymount/movie /mymount/move-ssh-read-write
do
    if [ -d "$directory/Mission, The" ]
    then
        basedir="$directory"
        break
    fi
done

if [ "$basedir" = "" ]
then
    echo "$0: Error: Could not find a movie directory. Exiting without ripping." 1>&2
    exit 1
fi

full_path="$basedir"/"$name"/makemkv

# Check whether the target directory already exists.
if [ -d "$full_path" ]
then
    echo "$full_path already exists - continue? (y/n)"
    while read -r line
    do
        case "$line" in
            y)
                break
                ;;
            n)
                echo "$0: Exiting without ripping" 1>&2
                exit 1
                ;;
        esac
    done
fi

mkdir -p "$full_path"

# Rip the whole bluray disc.  I tried one title at a time, but it just wasn't working for me.  But this is almost as nice, and
# easier to use, and works well.
makemkvcon mkv dev:"$source" all "$full_path"

cd "$full_path"

# makemkvcon seems to have a weird idea of what permissions bits should look like - so fix that.
chmod 644 ./*

# Downsample the resolution, preserving the subtitles and audio channels.
for mkvfile in ./*.mkv
do
    case "$mkvfile" in
        *.ds.mkv)
            continue
            ;;
    esac
    brmkvtodvdmkv "$mkvfile"
done

# Remove any .mkv files that are not downsampled.
shopt -s nullglob
for mkvfile in ./*.mkv
do
    case "$mkvfile" in
        *.ds.mkv)
            continue
            ;;
    esac
    rm "$mkvfile"
done