#!/usr/bin/env bash

# Bash for Archivists
# Part 3: Advanced Level
# 2020-07-07


SCRIPT_NAME="$(basename "${0}")"
[[ -d '/tmp/Bash_for_Archivists' ]] || mkdir '/tmp/Bash_for_Archivists'
LOG_FILE="$(mktemp /tmp/Bash_for_Archivists/day_5_$(date +'%H%M%S').XXXXXXXXXX)"


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

unset input_file
unset output_file
unset mode


# 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) -i INPUT_FILE -o OUTPUT_FILE
  ${SCRIPT_NAME} -h
Parameters:
  -a  generate an access file
  -m  generate a mezzanine file
  -i  define the INPUT_FILE
  -o  define the OUTPUT_FILE
  -h  display this help
EOF
    exit 0
}


# get timestamp
timestamp() {
    date +'[%T]'
}


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

    if (( $# == 0 )); then
        prompt_error "No input file passed."
    elif [[ ! -f "${in_file}" ]]; then
        prompt_error "'${input_file}' is not a file."
    elif ffprobe "${in_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
verify_output() {
    local in_file="${1}"

    if (( $# == 0 )); then
        prompt_error "No output file passed."
    elif echo '' > "${in_file}"; (( $? != 0 )); then
        prompt_error "Cannot create a file '${in_file}'."
    else
        rm "${in_file}"
    fi

    return 0
}


# generate an access file from a mezzanine file
make_access() {
    local in_file="${1}"
    local out_file="${2}"

    echo "$(timestamp) Generating access file '${out_file}'..." | tee -a "${LOG_FILE}"
    ffmpeg \
        -i "${in_file}" \
        -c:v libx264 -preset veryslow -crf 18 \
        -pix_fmt yuv420p -movflags +faststart \
        "${out_file}" >> "${LOG_FILE}" 2>&1
    (( $? != 0 )) && prompt_error "Script stopped, see '${LOG_FILE}'."
}


# generate a mezzanine file from an archive master
make_mezzanine() {
    local in_file="${1}"
    local out_file="${2}"

    echo "$(timestamp) Generating mezzanine file '${out_file}'..." | tee -a "${LOG_FILE}"
    ffmpeg \
        -framerate 24 -f image2 \
        -i "${in_file}" \
        -c:v prores_ks -profile:v 3 \
        "${out_file}" >> "${LOG_FILE}" 2>&1
    (( $? != 0 )) && prompt_error "Script stopped, see '${LOG_FILE}'." || return 0
}


# generate frame MD5 checksums
make_frame_MD5() {
    local in_file="${1}"
    local out_file="${in_file%.*}_${in_file##*.}_frame.md5"

    echo "$(timestamp) Generating frame MD5 checksums of '${out_file}'..." | tee -a "${LOG_FILE}"
    ffmpeg -y -i "${in_file}" -f framemd5 "${out_file}" &>/dev/null
    (( $? != 0 )) && prompt_error "Script stopped, see '${LOG_FILE}'." || return 0
}


# generate file's MD5 checksum
make_MD5() {
    local in_file="${1}"
    local out_file="${in_file%.*}_${in_file##*.}.md5"

    echo "$(timestamp) Generating MD5 checksum of '${out_file}'..." | tee -a "${LOG_FILE}"
    md5 -r "${in_file}" > "${out_file}"
    (( $? != 0 )) && prompt_error "Script stopped, see '${LOG_FILE}'." || return 0
}


# parse provided input
while getopts ":i:o:amh" opt; do
    case "${opt}" in
        i) input_file="${OPTARG}" ;;
        o) output_file="${OPTARG}" ;;
        a) mode='access' ;;
        m) mode='mezzanine' ;;
        h) prompt_help ;;
        :) prompt_error "The parameter '-${OPTARG}' requires a value." ;;
        *) prompt_error "Option '-${OPTARG}' is not valid." ;;
    esac
done


# verify provided input
echo "$(timestamp) START" | tee "${LOG_FILE}"
if [[ "${mode}" == 'mezzanine' ]]; then
    number=$(echo "${input_file}" | grep -o -E '_[0-9]+.' | grep -o -E '[0-9]+')
    verify_input "${input_file%_*}_${number%?}1.${input_file##*.}"
else
    verify_input "${input_file}"
fi
verify_output "${output_file}"


# select mode and generate files
case "${mode}" in
    mezzanine)
        input_file_regex="${input_file%_*}_%0${#number}d.${input_file##*.}"
        make_mezzanine "${input_file_regex}" "${output_file}"
        ;;
    access) make_access "${input_file}" "${output_file}" ;;
    *) prompt_error "No mode (access or mezzanine) selected." ;;
esac

make_frame_MD5 "${output_file}"
make_MD5 "${output_file}"

echo "$(timestamp) END" | tee -a "${LOG_FILE}"
