#!/usr/bin/env bash

# Bash for Archivists
# Part 1: Beginner Level
# 2020-06-25


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


# display a help message and exit
prompt_help() {
    script_name="$(basename "${0}")"
    cat << 'EOF'
Usage:
  ${script_name}
  ${script_name} FILE
  ${script_name} -h
EOF
    exit 0
}


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


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


# 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 frame MD5 checksums (placeholder)
output_file="${input_file%.*}_${input_file##*.}_md5.txt"
ffmpeg -i "${input_file}" -f framemd5 "${output_file}"
