#!/usr/bin/env bash

# Bash Scripting for AVpres
# Third Session, course version
# 2022-02-01


# initialise variables
unset script_name
unset input_file
unset output_md5
unset output_framemd5


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


# display a help message and exit with 0
prompt_help() {
    script_name="$(basename "${0}")"
    cat << EOF

Usage:
  ${script_name}
  ${script_name} FILE
  ${script_name} -h

EOF
    exit 0
}


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


# if requested, display the help message
if [[ "${input_file}" == "-h" ]]; then
    prompt_help
fi


# verify that the input is valid
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 ffprobe "${input_file}" 2>&1 | grep "Invalid data found" >/dev/null; then
    prompt_error "'$(basename ${input_file})' is not an AV file."
fi


# generate the MD5 checksum of the file
output_md5="${input_file%.*}_${input_file##*.}_md5.txt"
md5sum "${input_file}" | sed "s#${input_file%/*}/##" > "${output_md5}"

# generate the frame MD5 checksum manifest of the file
output_framemd5="${input_file%.*}_${input_file##*.}_framemd5.txt"
ffmpeg -i "${input_file}" -f framemd5 "${output_framemd5}"
