#!/usr/bin/env bash

#==================================================================================================
#        NAME: Convert & Proxy Video - CPV
#        USAGE: cpv.sh [-i filename.xxx] convert file, or [-a] convert all .xxx files in directory
#
#  DESCRIPTION: Converts video files to .mkv with additional lower resolution proxy files
#      WEBSITE: https://www.elsewebdevelopment.com/
#
# REQUIREMENTS: FFmpeg installed in the $PATH
#       AUTHOR: David Else
#      COMPANY: Else Web Development
#      VERSION: 1.0
# add -vf drawtext="fontfile=/usr/share/fonts/cantarell/Cantarell-Regular.otf: text='Test Text'"
#==================================================================================================
set -eu
normal=$(tput sgr0)
red=$(tput setaf 1)
green=$(tput setaf 2)
suffix=".MTS" # tested .mp4
log="-loglevel warning"
strip_subs="-sn"

prompt_user() {
    clear
    echo -e "The following will be stream copied to .mkv into the current directory:\n${green}$1${normal}\n"
    read -p "Create additional proxy video files? (y/N) " -n 1
    echo
}

create_stream_copy() {
    local new_filename="${original_file%"$suffix"}.mkv"
    local command=(ffmpeg $log -i "$original_file"
        -c copy "$strip_subs"
        "$new_filename")
    "${command[@]}"
    echo "Created file ${green}$new_filename${normal}"
}

create_proxy_copy() {
    local video_settings="libx264 -preset ultrafast -crf 0 -vf scale=480:-1"
    local new_filename="${original_file%"$suffix"}-proxy.mkv"
    local command=(ffmpeg $log -i "$original_file"
        -c:v $video_settings
        -c:a copy "$strip_subs"
        "$new_filename")
    "${command[@]}"
    echo "Created file ${green}$new_filename${normal}"
}

create_files() {
    original_file="$1"
    create_stream_copy
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        create_proxy_copy
    fi
}

while getopts c:i:a opt; do
    case $opt in
    c)
        suffix="${OPTARG}"
        ;;
    i)
        # now we can't use different extensions for this option
        if [[ $OPTARG == *"$suffix" ]]; then
            prompt_user "\n$OPTARG"
            create_files "$OPTARG"
        else
            echo "${red}Invalid file extension, must be $suffix${normal}" && exit 1
        fi
        ;;

    a)
        files_preview=()
        for file_preview in *"$suffix"; do
            [ -f "$file_preview" ] || break
            files_preview+=("\n$file_preview")
        done

        : "${files_preview:="empty"}"
        if [ "$files_preview" == "empty" ]; then
            echo "${red}There are no files with the container $suffix${normal}" && exit 1
        fi

        prompt_user "${files_preview[*]}"

        for file in *"$suffix"; do
            [ -f "$file" ] || break
            create_files "$file"
        done
        ;;
    ?)
        exit
        ;;
    esac
done

shift $((OPTIND - 1))