#!/usr/bin/env bash

# Bash for Archivists
# Part 2: Intermediate Level
# 2020-06-30


RED='\033[1;31m'
BLUE='\033[1;34m'
NC='\033[0m'

SCRIPT_NAME="$(basename "${0}")"


# display a short help if no parameter is provided
if (( "${#}" == 0 )); then
    cat << EOF
Help:
  ${SCRIPT_NAME} -h
EOF
    exit 1
fi


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


# display a help message and exit
prompt_help() {
    cat << EOF
Syntax:
  ${SCRIPT_NAME} -a | -m | -h
Parameters:
  -a  generate an access file
  -m  generate a mezzanine file
  -h  display this help
EOF
    exit 0
}


# read input  ########
read_input() {
if (( "${#}" == 0 )); then
    echo -n "Please drag-and-drop a file: "
    read input_file
else
    input_file="${1}"
fi
}


# verify input  ########
verify_input() {
if (( "${#}" > 1 )); then
    prompt_error "too many arguments: ${#}."
elif [[ "${input_file}" == "" ]]; then
    prompt_error "no file passed."
elif [[ ! -f "${input_file}" ]]; then
    prompt_error "'${input_file}' is not a file."
elif [[ "${input_file}" == "${0}" ]]; then
    prompt_error "'$(basename ${input_file})' is... myself!"
elif ffprobe "${input_file}" 2>&1 | grep "Invalid data found" >/dev/null; then
    prompt_error "'$(basename ${input_file})' is not an AV file."
elif cat "${input_file}" | grep "#format: frame checksums" >/dev/null; then 
    prompt_error "'$(basename ${input_file})' is a frame MD5 checksum file."
fi
}


# generate an access file from a mezzanine file
make_access() {
    ffmpeg \
        -i testsrc2_ProRes.mkv \
        -c:v libx264 -preset veryslow -crf 18 \
        -pix_fmt yuv420p -movflags +faststart \
        testsrc2_H264.mp4
    exit 0
}


# generate a mezzanine file from an archive master
make_mezzanine() {
    ffmpeg \
        -framerate 24 -f image2 \
        -i TESTSRC2/testsrc2_%03d.dpx \
        -c:v prores_ks -profile:v 3 \
        testsrc2_ProRes.mkv
    exit 0
}


# generate frame MD5 checksums (placeholder)
#output_file="${input_file%.*}_${input_file##*.}_md5.txt"
#ffmpeg -i "${input_file}" -f framemd5 "${output_file}"


while getopts ":amh" opt; do
    case "${opt}" in
        a) make_access ;;
        m) make_mezzanine ;;
        h) prompt_help ;;
        *) prompt_error "Option '-${OPTARG}' is not valid." ;;
    esac
done
