#!/usr/bin/env bash
#
# Copyright (C) 2017,2024 Denis 'GNUtoo' Carikli <GNUtoo@cyberdimension.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

usage()
{
    echo "Usage: $0 [drive] backup <path> # Backup the DVD with ddrescue."
    echo "       $0 [drive] title         # Get the DVD title with dvdbackup."
    echo "       $0 [drive] decrypt       # Run mplayer to decrypt the DVD."
}

decrypt()
{
    drive="$1"

    vlc dvd://"${drive}"
}

rescue()
{
    drive="$1"
    path="$2"

    ddrescue -b 2048 "${drive}" "${path}.img" "${path}.log"
    ret=$?
    if [ ${ret} -eq 0 ] ; then
        eject "${drive}"
    fi
}

title()
{
    drive="$1"

    dvdbackup \
        -I \
        -i "${drive}" \
        2>/dev/null | \
            grep '^DVD-Video information of the DVD with title' | \
            sed 's#"$##' | sed 's#.*"##' | sed 's# #_#g'
}

#########
# title #
#########
if [ $# -eq 1 ] && [ "$1" = "title" ]  ; then
    title "/dev/sr0"
elif [ $# -eq 2 ] && [ "$2" = "title" ]  ; then
    title "$1"
##########
# rescue #
##########
elif [ $# -eq 2 ] && [ "$1" = "backup" ]  ; then
    rescue "/dev/sr0" "$2"
elif [ $# -eq 3 ] && [ "$2" = "backup" ]  ; then
    rescue "$1" "$3"
###########
# decrypt #
###########
elif [ $# -eq 1 ] && [ "$1" = "decrypt" ]  ; then
    decrypt "/dev/sr0"
elif [ $# -eq 2 ] && [ "$2" = "decrypt" ]  ; then
    decrypt "$1"
else
      usage
      exit 1
fi
