#!/usr/bin/env bash

# Bash Scripting for AVpres
# Fourth Session, solution script
# 2022-02-03


# initialise constant
SCRIPT_NAME="$(basename "${0}")"

# initialise variables
unset opt
unset algorithm
unset input_file
unset output_file


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


# display a minimal help message and exit with 1
prompt_mini_help() {
    cat << EOF
Help:
  ${SCRIPT_NAME} -h
EOF
    exit 1
}


# display a help message and exit with 0
prompt_help() {
    cat << EOF

Syntax:
  ${SCRIPT_NAME} -m | -s | -h
Parameters:
  -m  generate MD5 checksum
  -s  generate SHA-1 checksum
  -h  display this help

EOF
    exit 0
}


# generate the checksum of the file and exit with 0
make_checksum() {
    case "${1}" in
        md5)  algorithm="md5" ;;
        sha1) algorithm="sha1" ;;
        *)    prompt_error ;;
    esac

    output_file="${input_file%.*}_${input_file##*.}_${algorithm}.txt"
    ${algorithm}sum "${input_file}" > "${output_file}"
    exit 0
}


# parse and process the provided input
(( "${#}" == 0 )) && prompt_mini_help
while getopts ":msh" opt; do
    case "${opt}" in
        m) input_file="mandelbrot_H264.mp4"
           make_checksum "md5"
           ;;
        s) input_file="mandelbrot_H264.mp4"
           make_checksum "sha1"
           ;;
        h) prompt_help ;;
        *) prompt_error "Option '-${OPTARG}' is not valid." ;;
    esac
done
