#!/usr/bin/env bash

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

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

# initialise variables
unset input_folder
unset algorithm



# 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}"
    local line
    local payload
    local size
    local number
    local tmp_manifest="$(mktemp -q "/tmp/tmp_${SCRIPT_NAME}.XXXXXXXXXX")"
    local version_regex='1.0|0.9[3-7]'  # 1.0 and from 0.93 to 0.97
    local date_regex='20(0[789]|1[0-9]|2[012])-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])'

    echo -e "${BLUE}Please wait while verifying that global structure...${NC}"

    # verify 'bagit.txt' file
    if [[ ! -f "${in_folder}/bagit.txt" ]]; then
        prompt_error "The 'bagit.txt' file is missing."
    else
        echo -e "> ${BLUE}OK${NC} 'bagit.txt' found"
    fi
    if ! grep 'BagIt-Version:' < "${in_folder}/bagit.txt" | grep -E ${version_regex}
    then
        prompt_error "'BagIt-Version' is missing or not valid."
    fi
    if ! grep 'Tag-File-Character-Encoding:' < "${in_folder}/bagit.txt" \
        | grep -E 'UTF-8' &> /dev/null
    then
        prompt_error "'Tag-File-Character-Encoding' is missing or not valid."
    fi

    # verify 'data/' folder
    if [[ ! -d "${in_folder}/data" ]]; then
        prompt_error "The 'data/' folder is missing."
    else
        echo -e "> ${BLUE}OK${NC} 'data/' found"
    fi

    # verify 'manifest-<algorithm>.txt' checksum manifest
    if [[ -f "${in_folder}/manifest-md5.txt" ]]; then
        algorithm='md5'
        md5="${md5:-$(which md5sum)}"
        echo -e "> ${BLUE}OK${NC} 'manifest-${algorithm}.txt' found"
    elif [[ -f "${in_folder}/manifest-sha1.txt" ]]; then
        algorithm='sha1'
        sha1="${sha1:-$(which sha1sum)}"
        echo -e "> ${BLUE}OK${NC} 'manifest-${algorithm}.txt' found"
    elif [[ -f "${in_folder}/manifest-sha256.txt" ]]; then
        algorithm='sha256'
        sha256="${sha256:-$(which sha256sum)}"
        echo -e "> ${BLUE}OK${NC} 'manifest-${algorithm}.txt' found"
    elif [[ -f "${in_folder}/manifest-sha512.txt" ]]; then
        algorithm='sha512'
        sha512="${sha512:-$(which sha512sum)}"
        echo -e "> ${BLUE}OK${NC} 'manifest-${algorithm}.txt' found"
    else
        prompt_error "The 'manifest-<algorithm>.txt' file is missing."
    fi

    # check if external hash checksum command is running
    if ! command -v ${!algorithm} &> /dev/null; then
        prompt_error "'${!algorithm}' is failing."
    fi

    # verify 'tagmanifest-<algorithm>.txt' file, if present
    if [[ -f "${in_folder}/tagmanifest-${algorithm}.txt" ]]; then
        echo -e "> ${BLUE}OK${NC} 'tagmanifest-${algorithm}.txt' found"
        if ! ${!algorithm} "${in_folder}"/*.txt > "${tmp_manifest}"; then
            prompt_error
        fi
        if ! diff -b <(sort < "${in_folder}/tagmanifest-${algorithm}.txt") \
            <(grep -v tagmanifest-${algorithm}.txt < "${tmp_manifest}" \
            | sed "s#${in_folder}/##g" | sort) 2>&1
        then
            prompt_error "Error: 'tagmanifest-${algorithm}.txt' don't match."
        else
            echo -e "> ${BLUE}OK${NC} 'tagmanifest-${algorithm}.txt' is correct"
        fi
    else
        echo -e "> ${RED}no${NC} 'tagmanifest-${algorithm}.txt' found"
    fi

    # verify 'bag-info.txt' file
    if [[ -f "${in_folder}/bag-info.txt" ]]; then
        echo -e "> ${BLUE}OK${NC} 'bag-info.txt' found"
        line="$(grep 'Bagging-Date' < "${in_folder}/bag-info.txt")"
        if [[ ! $(echo "${line}" | grep -E "${date_regex}") ]]; then
            prompt_error "'${line}' is not valid."
        fi
        line="$(grep 'Payload-Oxum' < "${in_folder}/bag-info.txt")"
        payload="$(echo "${line}" | grep -oE '[0-9]+.[0-9]+')"
        for f in $(find ${in_folder}/data -type f); do
            (( size += $(wc -c < ${f} | bc) ))
        done
        number=$(find ${in_folder}/data -type f | wc -l | bc)
        if [[ "${payload}" != "${size}.${number}" ]]; then
            prompt_error "'${line}' is not valid: '${size}.${number}' is expected."
        else
            echo -e "> ${BLUE}OK${NC} 'Payload-Oxum' is correct"
        fi
    else
        echo -e "> ${RED}no${NC} 'bag-info.txt' found"
    fi

    ######## presence of other files

    return 0
}


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

    echo -e "${BLUE}Please wait while checking data against manifest...${NC}"

    ######## 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}"
