#!/usr/bin/env bash

# Bash Scripting for AVpres
# Eighth Session: verify BagIt archive, draft for course script
# 2022-02-17

# initialise constants
SCRIPT_NAME="$(basename "${0}")"
RED='\033[1;31m'
BLUE='\033[1;34m'
NC='\033[0m'

# initialise variable
unset input_folder


# if no input is provided, then display a minimal help message and exit with 1
if (( "${#}" == 0 )); then
    cat << EOF
Help:
  ${SCRIPT_NAME} -h
EOF
    exit 1
fi


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


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

Syntax:
  ${SCRIPT_NAME} -i <input_folder>
  ${SCRIPT_NAME} -h

Parameters:
  -i  path and name of the folder containing the BagIt archive
  -h  display this help

EOF
    exit 0
}


# verify input (and normalise path if needed)
verify_input() {
    local in_folder="${1}"

    if [[ ! "${in_folder}" ]]; then
        prompt_error "No input folder passed."
    elif [[ ! -d "${in_folder}" ]]; then
        prompt_error "'${in_folder}' is not a folder."
    elif [[ "${in_folder%/*}" == "${in_folder}" ]]; then
        input_folder="${PWD}/${in_folder}"
    fi

    if [[ ! $(ls -A "${input_folder}") || $(ls -A "${input_folder}") == '.DS_Store' ]]; then
        prompt_error "'${in_folder}' is empty."
    fi

    return 0
}


# check if the BagIt archive is complete
check_complete() {
    local in_folder="${1}"

    # verify 'bagit.txt' file

    # verify 'data/' folder

    # verify 'manifest-<algorithm>.txt' checksum manifest

    # check if external hash checksum command is running

    # verify 'tagmanifest-<algorithm>.txt' file, if present

    # verify 'bag-info.txt' file

    # presence of other files

    return 0
}


# check if the BagIt archive is valid
check_valid() {
    local in_folder="${1}"

    # verify 'manifest-<algorithm>.txt' checksum manifest

    return 0
}


# parse and process provided input
(( $# == 0 )) && print_prompt
while getopts ":i:h" opt; do
    case "${opt}" in
        i) if [[ "${OPTARG:0:1}" == '-' ]]; then
              prompt_error "The option '-i' requires an argument."
           else
              input_folder="${OPTARG}"
           fi ;;
        h) prompt_help ;;
        :) prompt_error "The option '-${OPTARG}' requires an argument." ;;
        *) prompt_error "The option '-${OPTARG}' is not valid." ;;
    esac
done


# check if provided input is valid
verify_input "${input_folder}"

# check if the BagIt archive is complete
check_complete "${input_folder}"

# check if the BagIt archive is valid
check_valid "${input_folder}"
