#!/usr/bin/env bash

# Bash Scripting for AVpres
# Ninth Session: update a checksum manifest, course script
# 2022-02-22

# initialise constants
SCRIPT_NAME="$(basename "${0}")"
CONFIG_FILE="${HOME}/.config/AMIA_Bash/${SCRIPT_NAME}.txt"
RED='\033[1;31m'
BLUE='\033[1;34m'
NC='\033[0m'
algorithm_regex='^(md5|sha1|sha256|sha512)$'

# load configuration file if any and initialise default values
[[ -f "${CONFIG_FILE}" ]] && . "${CONFIG_FILE}"
algorithm="${algorithm:-md5}"
tool="${tool:-md5sum}"

# initialise variables
unset input_folder
unset chesksum_manifest


# 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 <folder> [-m <manifest>] [-a <algorithm>] [-t <tool>]
  ${SCRIPT_NAME} -h

Parameters:
  -i  path and name of the folder containing
  -m  path, name and extension of the checksum manifest
      (default is '<input_folder>_${algorithm}.txt')
  -a  checksum algorithm: md5, sha1, sha256, sha512 (default is '${algorithm}')
  -t  chesksum tool (default is '${tool}')
  -h  display this help

EOF
    exit 0
}


# verify input folder (and normalise path if needed)
verify_folder() {
    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
}


# verify checksum manifest
verify_manifest() {
    local in_manif="${1}"

    if [[ ! "${in_manif}" ]]; then
        prompt_error "No manifest file passed."
    elif [[ ! -f "${in_manif}" ]]; then
        prompt_error "'${in_manif}' is not a file."
    fi

    return 0
}


# verify that checksum algorithm is valid
verify_algorithm() {
    local algo="${1}"

    if [[ ! $(echo "${algo}" | grep -E "${algorithm_regex}") ]]; then
        prompt_error "'${algo}' is not a valid algorithm."
    fi

    return 0
}


# verify that checksum tool for chosen algorithm is running
verify_tool() {
    local tool="${1}"

    if ! command -v "${tool}" &> /dev/null; then
        prompt_error "Checksum tool '${tool}' was not found."
    fi

    return 0
}


# update checksum manifest
update_manifest() {
    local in_folder="${1}"
    local in_manif="${2}"
    local tmp_1
    local tmp_2
    local nb_1
    local nb_2
    local line

    # only in the folder
    tmp_1=$(comm -23 <(ls "${in_folder}") <(awk '{print $2}' < "${in_manif}"))
    if [[ -n "${tmp_1}" ]]; then
        nb_1=$(echo "${tmp_1}" | wc -l | bc)
    else
        nb_1=0
    fi

    # only in the manifest
    tmp_2=$(comm -13 <(ls "${in_folder}") <(cat "${in_manif}" | awk '{print $2}'))
    if [[ -n "${tmp_2}" ]]; then
        nb_2=$(echo "${tmp_2}" | wc -l | bc)
    else
        nb_2=0
    fi

    if [[ -n "${tmp_1}" ]] && [[ -n "${tmp_2}" ]] && [[ "${tmp_1}" != "${tmp_1}" ]]; then
        prompt_error "Both folder and checksum manifest have been modified."
    elif (( "${nb_1}" == "${nb_2}" )); then
        echo -e "${BLUE}The number of files equals the number of checksums.${NC}"
        exit 0
    elif (( "${nb_1}" > "${nb_2}" )); then

        # compute checksum and add it to manifest
        while IFS= read -r line; do
            "${tool}" "${in_folder}/${line}" | sed "s#${in_folder}/*##" >> "${in_manif}"
        done < <(echo "${tmp_1}")

        echo -e "${BLUE}The missing checksums have been added to the manifest.${NC}"
    elif (( "${nb_1}" < "${nb_2}" )); then

        # delete checksum from manifest
        while IFS= read -r line; do
            grep -v "${line}" "${in_manif}" > tmp_file && mv tmp_file "${in_manif}"
        done < <(echo "${tmp_2}")

        echo -e "${BLUE}The superfluous checksums have been deleted from the manifest.${NC}"
    else
        prompt_error
    fi
}


# parse and process provided input
(( $# == 0 )) && print_prompt
while getopts ":i:m:a:t: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 ;;
        m) if [[ "${OPTARG:0:1}" == '-' ]]; then
              prompt_error "The option '-m' requires an argument."
           else
              checksum_manifest="${OPTARG}"
           fi ;;
        a) if [[ "${OPTARG:0:1}" == '-' ]]; then
              prompt_error "The option '-a' requires an argument."
           else
              algorithm="${OPTARG}"
           fi ;;
        t) if [[ "${OPTARG:0:1}" == '-' ]]; then
              prompt_error "The option '-t' requires an argument."
           else
              tool="${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_folder "${input_folder}"
verify_tool "${tool}"
verify_algorithm "${algorithm}"
if [[ -z "${checksum_manifest}" ]]; then
    checksum_manifest="${input_folder}_${algorithm}.txt"
fi
verify_manifest "${checksum_manifest}"

# update checksum manifest
update_manifest "${input_folder}" "${checksum_manifest}"
