#!/usr/bin/env bash

# Bash Scripting for AVpres
# Sixth Session: make mezzanine file, exercice script
# 2022-02-10

# initialise constants
SCRIPT_NAME="$(basename "${0}")"
RED='\033[1;31m'
BLUE='\033[1;34m'
NC='\033[0m'

# initialise presets
declare -A prores_types
prores_types=([ProRes 422 proxy]='0' [ProRes 422 LT]='1')
prores_types+=([ProRes 422 standard]='2' [ProRes 422 HQ]='3')
prores_types+=([ProRes 4444]='4' [ProRes 4444 XQ]='5')

# initialise variables
unset input_file
unset output_file
unset prores_number
unset prores_name


# if no input is provided, then display a minimal help message and exit with 1
if (( "${#}" == 0 )); then
    cat << EOF
Help:
  ${SCRIPT_NAME} -h
EOF
    exit 1
fi


# display an error message and exit with 1
prompt_error() {
    echo -e "${RED}Error: ${1:-unknown error.\a}${NC}"
    exit 1
}


# display a help message and exit with 0
prompt_help() {
    cat << EOF

Syntax:
  ${SCRIPT_NAME} -i <input_file> -o <output_file> [-p <ProRes_flavour>]
  ${SCRIPT_NAME} -h

Parameters:
  -i  path, name and extension of the input file
  -o  path, name and extension of the output file
  -p  one of 'ProRes 4444 XQ', 'ProRes 4444', 'ProRes 422 HQ' (default),
      'ProRes 422 standard', 'ProRes 422 LT' or 'ProRes 422 proxy'
  -h  display this help

EOF
    exit 0
}


# verify input file
verify_input() {
    local in_file="${1}"

    if [[ "${in_file}" == '' ]]; then
        prompt_error "No input file passed."
    elif [[ ! -f "${in_file}" ]]; then
        prompt_error "'${in_file}' is not a file."
    elif ffprobe "${input_file}" 2>&1 | grep "Invalid data found" >/dev/null; then
        prompt_error "'$(basename ${input_file})' is not an AV file."
    fi

    return 0
}


# verify output file
verify_output() {
    local out_file="${1}"
    local kbd

    if [[ -f "${out_file}" ]]; then
        echo -e "${BLUE}Warning: '${out_file}' already exist.${NC}"
        echo -n "Continue and overwrite? (y|N) "
        read -rn 1 kbd
        echo
        if [[ "${kbd}" != [Yy] ]]; then
            prompt_error "Aborted by user."
        fi
    fi

    if [[ "${out_file}" == '' ]]; then
        prompt_error "No output file passed."
    elif echo "${out_file##*.}" | grep -E "^(mov|mkv|mxf)$"; (( $? != 0 )); then
        prompt_error "'${out_file##*.}' is not a valid file format."
    elif echo '' > "${out_file}"; (( $? != 0 )); then
        prompt_error "Cannot create an output file '${out_file}'."
    fi

    return 0
}


# verify ProRes type
verify_prores() {
    local pr_name="${1}"

    if [[ "${pr_name}" == '' ]]; then
        prores_number='3'
    else
        prores_number="${prores_types[$pr_name]}"
    fi

    if [[ "${prores_number}" == '' ]]; then
        prompt_error "'${pr_name}' is not a valid ProRes type."
    fi

    return 0
}


# generate the AV file and exit with 0
make_file() {
    local in_file="${1}"
    local out_file="${2}"

    echo -e "${BLUE}Please wait...${NC}"
    ffmpeg \
        -i "${in_file}" \
        -c:v prores_ks \
        -profile:v  "${prores_number}"\
        -y \
        "${out_file}"
    if (( $? != 0 )); then
        [[ -f "${out_file}" ]] && rm "${out_file}"
        prompt_error "The file '$(basename ${out_file})' could not be generated."
    else
        echo -e "${BLUE}... done.${NC}"
        exit 0
    fi
}


# parse and process the provided input
while getopts ":i:o:p:h" opt; do
    case "${opt}" in
        i) if [[ "${OPTARG:0:1}" == '-' ]]; then
              prompt_error "Error: The option '-i' requires an argument."
           else
              input_file="${OPTARG}"
           fi ;;
        o) if [[ "${OPTARG:0:1}" == '-' ]]; then
              prompt_error "Error: The option '-o' requires an argument."
           else
              output_file="${OPTARG}"
           fi ;;
        p) if [[ "${OPTARG:0:1}" == '-' ]]; then
              prompt_error "Error: The option '-p' requires an argument."
           else
              prores_name="${OPTARG}"
           fi ;;
        h) prompt_help ;;
        :) prompt_error "Option '-${OPTARG}' requires an argument." ;;
        *) prompt_error "Option '-${OPTARG}' is not valid." ;;
    esac
done

# check if provided input is valid
verify_input "${input_file}"
verify_prores "${prores_name}"
verify_output "${output_file}"

# generate the access file
make_file "${input_file}" "${output_file}"
