#!/usr/bin/env bash

# Bash for Archivists
#
# Copyright (c) 2020 by Everyone on Earth
#
# This Bash script is released under a 3-Clause BSD License and is provided
# "as is" without warranty or support of any kind.

SCRIPT_NAME="$(basename "$0")"
VERSION='2020-07-12'

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

FF_G_OPT_FV="${FF_G_OPT_FV:--n}"
FF_I_OPT_FV="${FF_I_OPT_FV:--framerate 24 -f image2}"
FF_O_OPT_FV="${FF_O_OPT_FV:--c:v prores_ks -profile:v 3}"
FF_G_OPT_VV="${FF_G_OPT_VV:--n}"
FF_I_OPT_VV="${FF_I_OPT_VV}"
FF_O_OPT_VV="${FF_O_OPT_VV:--c:v libx264 -preset veryslow -crf 18 -pix_fmt yuv420p -movflags +faststart}"

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 a help message and exit
prompt_help() {
    cat << EOF
Syntax:
  ${SCRIPT_NAME} (-v | -f) -i INPUT_FILE -o OUTPUT_FILE
  ${SCRIPT_NAME} -h | -x
Parameters:
  -v  transcode "video to video"
  -f  transcode "film to video"
  -i  define the INPUT_FILE
  -o  define the OUTPUT_FILE
  -h  display this help
  -x  display FFmpeg options and their default arguments
Dependency:
  ffmpeg
EOF
    exit 0
}


# display the FFmpeg options and their default arguments
prompt_options() {
    cat << EOF
FFmpeg options with their default arguments:
  --ff_g_opt_fv="${FF_G_OPT_FV}"
  --ff_i_opt_fv="${FF_I_OPT_FV}"
  --ff_o_opt_fv="${FF_O_OPT_FV}"
  --ff_g_opt_vv="${FF_G_OPT_VV}"
  --ff_i_opt_vv="${FF_I_OPT_VV}"
  --ff_o_opt_vv="${FF_O_OPT_VV}"
EOF
    exit 0
}


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


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


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

    if [[ "${in_file}" == "" ]] || [[ "${in_file}" == "_." ]]; then
        prompt_error "No input file passed."
    elif [[ ! -f "${in_file}" ]]; then
        prompt_error "'${in_file}' is not an input 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 out_file="${1}"

    if [[ "${out_file}" == "" ]]; then
        prompt_error "No output file passed."
    elif echo '' > "${out_file}_tmp"; (( $? != 0 )); then
        prompt_error "Cannot create an output file '${out_file}'."
    else
        rm "${out_file}_tmp"
    fi

    return 0
}


# transcode between two stream-based formats ("video to video")
stream_2_stream() {
    local in_file="${1}"
    local out_file="${2}"

    echo "$(timestamp) Generating '${out_file}'..." | tee -a "${LOG_FILE}"
    echo "$(timestamp) ffmpeg ${FF_G_OPT_VV} ${FF_I_OPT_VV} -i ${in_file} ${FF_O_OPT_VV} ${out_file}" >> "${LOG_FILE}"
    ffmpeg ${FF_G_OPT_VV} ${FF_I_OPT_VV} -i "${in_file}" ${FF_O_OPT_VV} "${out_file}" >> "${LOG_FILE}" 2>&1

    (( $? != 0 )) && prompt_error "Fatal error, see '${LOG_FILE}'." || return 0
}


# transcode an image-based format into a stream-based format ("film to video")
image_2_stream() {
    local in_file="${1}"
    local out_file="${2}"

    echo "$(timestamp) Generating '${out_file}'..." | tee -a "${LOG_FILE}"
    echo "$(timestamp) ffmpeg ${FF_G_OPT_FV} ${FF_I_OPT_FV} -i ${in_file} ${FF_O_OPT_FV} ${out_file}" >> "${LOG_FILE}"
    ffmpeg ${FF_G_OPT_FV} ${FF_I_OPT_FV} -i "${in_file}" ${FF_O_OPT_FV} "${out_file}" >> "${LOG_FILE}" 2>&1

    (( $? != 0 )) && prompt_error "Fatal error, 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 '${out_file}'..." | tee -a "${LOG_FILE}"
    echo "$(timestamp) ffmpeg -y -i ${in_file} -f framemd5 ${out_file}" >> "${LOG_FILE}"
    ffmpeg -y -i "${in_file}" -f framemd5 "${out_file}" &> /dev/null

    (( $? != 0 )) && prompt_error "Fatal error, 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 '${out_file}'..." | tee -a "${LOG_FILE}"
    echo "$(timestamp) md5 -r ${in_file}" >> "${LOG_FILE}"
    ${MD5} "${in_file}" > "${out_file}"

    (( $? != 0 )) && prompt_error "Fatal error, see '${LOG_FILE}'." || return 0
}


# parse provided input
while getopts ":i:o:vf-:hx" opt; do
    case "${opt}" in
        i) if [[ "${OPTARG:0:1}" == "-" ]]; then
               prompt_error "${RED}Error: The parameter '-i' requires a value.${NC}"
           else
               input_file="${OPTARG}"
           fi ;;
        o) if [[ "${OPTARG:0:1}" == "-" ]]; then
               prompt_error "${RED}Error: The parameter '-o' requires a value.${NC}"
           else
               output_file="${OPTARG}"
           fi ;;
        v) mode='video' ;;
        f) mode='film' ;;
        -) case "${OPTARG}" in
               ff_g_opt_fv=?*) FF_G_OPT_FV="${OPTARG#*=}" ;;
               ff_i_opt_fv=?*) FF_I_OPT_FV="${OPTARG#*=}" ;;
               ff_o_opt_fv=?*) FF_O_OPT_FV="${OPTARG#*=}" ;;
               ff_g_opt_vv=?*) FF_G_OPT_VV="${OPTARG#*=}" ;;
               ff_i_opt_vv=?*) FF_I_OPT_VV="${OPTARG#*=}" ;;
               ff_o_opt_vv=?*) FF_O_OPT_VV="${OPTARG#*=}" ;;
               *) prompt_error "FFmpeg option '--${OPTARG}' is wrong." ;;
           esac ;;
        h) prompt_help ;;
        x) prompt_options ;;
        :) prompt_error "The parameter '-${OPTARG}' requires a value." ;;
        *) prompt_error "Option '-${OPTARG}' is not valid." ;;
    esac
done


# check if Bash version ≥ 4 is running
#if (( $(bash -c 'echo ${BASH_VERSION%%.*}') < 4 )); then
#    prompt_error "Bash version 4 or earlier is needed."
#fi


# check if FFmpeg is running
if ! command -v ffmpeg &> /dev/null; then
    prompt_error "FFmpeg is not installed."
fi


# check if am MD5 is running
if command -v md5 &> /dev/null; then
    MD5='md5 -r'
elif command -v md5sum &> /dev/null; then
    MD5='md5sum'
else
    prompt_error "No MD5 utility found."
fi


# verify provided input
if [[ "${mode}" == 'film' ]]; then
    first_file=$(ls "${input_file%/*}/" | sort | head -n 1)
    start_number=$(echo "${first_file}" | grep -o -E '_[0-9]+.' | grep -o -E '[0-9]+')
    FF_I_OPT_FV+=" -start_number ${start_number}"
    verify_input "${input_file%_*}_${start_number}.${input_file##*.}"
else
    verify_input "${input_file}"
fi
verify_output "${output_file}"


echo "$(timestamp) ${SCRIPT_NAME} ${VERSION}" > "${LOG_FILE}"
echo "$(timestamp) START" | tee -a "${LOG_FILE}"

# select mode and generate files
case "${mode}" in
    film)
        digit_pattern=$(echo "${input_file}" | grep -o -E '_[0-9]+.' | grep -o -E '[0-9]+')
        input_file_regex="${input_file%_*}_%0${#digit_pattern}d.${input_file##*.}"
        image_2_stream "${input_file_regex}" "${output_file}"
        ;;
    video)
        stream_2_stream "${input_file}" "${output_file}"
        ;;
    *) prompt_error "No mode selected ('-f' or '-v')." ;;
esac

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

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