#!/usr/bin/env bash

# Update the checksum manifest of a folder.
#
# Copyright (c) 2021-2026 by Reto Kromer <https://reto.ch/>
#
# This Bash script is released under a 3-Clause BSD License and is provided
# "as is" without warranty or support of any kind.


# initialise constants
VERSION='2025-12-04'
SCRIPT_NAME="$(basename "$0")"
CONFIG_FILE="${HOME}/.config/AVpres/Bash_AVpres/${SCRIPT_NAME}.txt"
RED='\033[1;31m'
BLUE='\033[1;34m'
NC='\033[0m'

# load configuration file if any and initialise default values
[[ -f "${CONFIG_FILE}" ]] && . "${CONFIG_FILE}"
default_algorithm="${default_algorithm:-xxh128}"
crc32="${crc32:-$(which crc32)}"
md5="${md5:-$(which md5sum)}"
sha1="${sha1:-$(which sha1sum)}"
sha256="${sha256:-$(which sha256sum)}"
sha512="${sha512:-$(which sha512sum)}"
xxh32="${xxh32:-$(which xxhsum) -H32}"
xxh64="${xxh64:-$(which xxhsum) -H64}"
xxh128="${xxh128:-$(which xxhsum) -H128}"
suffix="${suffix:-_${default_algorithm}}"
extension="${extension:-txt}"

# initialise another default value
algorithm_regex='^(crc32|md5|sha1|sha256|sha512|xxh32|xxh64|xxh128)$'

# initialise variables
unset algorithm
unset input_folder


# get date-and-time stamp
date_time() {
  TZ='UTC' date +'[%F %T %Z]'
}


# start log file
[[ -d '/tmp/AVpres' ]] || mkdir -p '/tmp/AVpres'
LOG_FILE="$(mktemp "/tmp/AVpres/${SCRIPT_NAME}.XXXXXXXXXX")"
TMP_MANIFEST="$(mktemp -q "/tmp/AVpres/tmp_${SCRIPT_NAME}.XXXXXXXXXX")"
echo "$(date_time) ${SCRIPT_NAME} ${VERSION}" > "${LOG_FILE}"
echo "$(date_time) $0 $*" >> "${LOG_FILE}"
echo "$(date_time) START" >> "${LOG_FILE}"

# check that Bash 3.2 or later is running
if ! printf '%s\n%s\n' "$(bash -c 'echo ${BASH_VERSION}')" "3.2" | sort -rVC; then
  echo -e "${BLUE}Warning: This 'bash' binary is very old."
  echo -e "We strongly recommend that you use the current version 5.3.${NC}"
fi


# print error message and exit with status 1
abort() {
  echo -e "${RED}${1:-An unknown error occurred.\a}${NC}"
  echo "$(date_time) ${1:-An unknown error occurred.}" >> "${LOG_FILE}"
  rm "${TMP_MANIFEST}"
  echo "$(date_time) END" >> "${LOG_FILE}"
  exit 1
}


# print a minimal help message and exit with status 1
print_prompt() {
  echo "$(date_time) print prompt" >> "${LOG_FILE}"
  cat << EOF
Help:
  ${SCRIPT_NAME} -h
EOF
  rm "${TMP_MANIFEST}"
  echo "$(date_time) END" >> "${LOG_FILE}"
  exit 1
}


# print the help message and exit with status 0
print_help() {
  local tmp
  if [[ -f "${CONFIG_FILE}" ]]; then
    tmp="local configuration file found and loaded"
  else
    tmp="no local configuration file found on this computer"
  fi

  echo "$(date_time) print help" >> "${LOG_FILE}"
  cat << EOF

Usage:
  ${SCRIPT_NAME} -i <input_folder> [-m <input_manifest>]
  ${SCRIPT_NAME} -h | -x
Options:
  -i  input folder
  -m  manifest file (default is '<input_folder>${suffix}.${extension}')
  -h  this help
  -x  advanced options with their default arguments
      (${tmp})
Dependency:
  xxhsum (default), md5sum, sha1sum, sha256sum, sha512sum or crc32
See also:
  man ${SCRIPT_NAME}
  https://avpres.net/Bash_AVpres/
About:
  Abstract: Update a checksum manifest of a folder
  Version:  ${VERSION}

EOF
  rm "${TMP_MANIFEST}"
  echo "$(date_time) END" >> "${LOG_FILE}"
  exit 0
}


# print advanced options with their default arguments and exit with status 0
print_options() {
  echo "$(date_time) print parameters" >> "${LOG_FILE}"
  if [[ -f "${CONFIG_FILE}" ]]; then
    cat << EOF

Local configuration file
  '${CONFIG_FILE}'
found and loaded.
EOF
  else
    cat << EOF

No local configuration file for '${SCRIPT_NAME}' found on this computer.
EOF
  fi
  cat << EOF

Checksum default parameters:
  --algorithm='${default_algorithm}'
  --crc32='${crc32}'
  --md5='${md5}'
  --sha1='${sha1}'
  --sha256='${sha256}'
  --sha512='${sha512}'
  --xxh32='${xxh32}'
  --xxh64='${xxh64}'
  --xxh128='${xxh128}'

Output file default parameters:
  --suffix='${suffix}'
  --extension='${extension}'

EOF
  rm "${TMP_MANIFEST}"
  echo "$(date_time) END" >> "${LOG_FILE}"
  exit 0
}


# check that hash checksum command is valid and running
check_algorithm() {
  local tmp_algorithm="${algorithm}"

  if [[ ! "${algorithm}" ]]; then
    algorithm="${default_algorithm}"
  else
    algorithm="$(echo "${algorithm}" | awk '{print tolower($0)}')"
    if [[ ! $(echo "${algorithm}" | grep -E "${algorithm_regex}") ]]; then
      abort "Error: Algorithm '${tmp_algorithm}' is not valid."
    fi
  fi

  if ! command -v ${!algorithm} &> /dev/null; then
    abort "Error: '${algorithm}' is failing."
  fi

  if [[ "${suffix}" != "_${algorithm}" \
    && "${algorithm}" != 'xxh128' \
    && "${suffix}" == '_xxh128' ]]
  then
    suffix="_${algorithm}"
  fi
  echo "$(date_time) ${algorithm}='${!algorithm}'" >> "${LOG_FILE}"

  return 0
}


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

  echo "$(date_time) verify input" >> "${LOG_FILE}"
  if [[ ! "${in_path}" ]]; then
    abort "Error: No input file or folder provided via '-i' or '--input'."
  elif [[ ! -d "${in_path}" ]]; then
    abort "Error: '${in_path}' is not a folder."
  elif [[ "${in_path%/*}" == "${in_path}" ]]; then
    input_folder="${PWD}/${in_path}"
  fi

  if [[ ! $(ls -A "${in_path}") || $(ls -A "${in_path}") == '.DS_Store' ]]; then
    abort "Error: '${in_path}' is empty."
  fi

  return 0
}


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

  echo "$(date_time) verify output" >> "${LOG_FILE}"
  if [[ ! "${in_manif}" ]]; then
    abort "Error: No output file provided via '-m' or '--manifest'."
  elif [[ ! -f "${in_manif}" ]]; then
    abort "Error: '${in_manif}' is not a file."
  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

  echo -e "${BLUE}Please wait while updating checksum manifest...${NC}"
  echo "$(date_time) updating checksum manifest" >> "${LOG_FILE}"

  # elements which are 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

  # elements which are only in the manifest
  tmp_2=$(comm -13 <(ls "${in_folder}") <(awk '{print $2}' < "${in_manif}"))
  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}"
    echo "The number of files equals the number of checksums." >> "${LOG_FILE}"
    echo "$(date_time) END" >> "${LOG_FILE}"
    exit 0
  elif (( "${nb_1}" > "${nb_2}" )); then

    # compute checksum and add it to manifest
    while IFS= read -r line; do
      ${!algorithm} "${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}"
    echo "The missing checksums have been added to the manifest." >> "${LOG_FILE}"
  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}"
    echo "The superfluous checksums have been deleted from the manifest." >> "${LOG_FILE}"
  else
    abort "Fatal error, see '${LOG_FILE}'."
  fi
}


# parse and process provided input
(( $# == 0 )) && print_prompt
while getopts ":i:m:-:hx" opt; do
  case "${opt}" in
    i) if [[ "${OPTARG:0:1}" == '-' ]]; then
         abort "Error: The option '-i' requires an argument."
       else
         input_folder="${OPTARG}"
       fi ;;
    m) if [[ "${OPTARG:0:1}" == '-' ]]; then
         abort "Error: The option '-m' requires an argument."
       else
         output_path="${OPTARG}"
       fi ;;
    -) case "${OPTARG}" in
         input=?*) input_folder="${OPTARG#*=}" ;;
         manifest=?*) output_path="${OPTARG#*=}" ;;
         suffix=?*) suffix="${OPTARG#*=}" ;;
         extension=?*) extension="${OPTARG#*=}" ;;
         algorithm=?*) algorithm="${OPTARG#*=}" ;;
         crc32=?*) crc32="${OPTARG#*=}" ;;
         md5=?*) md5="${OPTARG#*=}" ;;
         sha1=?*) sha1="${OPTARG#*=}" ;;
         sha256=?*) sha256="${OPTARG#*=}" ;;
         sha512=?*) sha512="${OPTARG#*=}" ;;
         xxh32=?*) xxh32="${OPTARG#*=}" ;;
         xxh64=?*) xxh64="${OPTARG#*=}" ;;
         xxh128=?*) xxh128="${OPTARG#*=}" ;;
         help) print_help ;;
         options) print_options ;;
         *) abort "Error: The option '--${OPTARG}' is not valid." ;;
       esac ;;
    h) print_help ;;
    x) print_options ;;
    :) abort "Error: The option '-${OPTARG}' requires an argument." ;;
    *) abort "Error: The option '-${OPTARG}' is not valid." ;;
  esac
done

# check that hash checksum command is running
check_algorithm

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

# check that provided output file is valid and normalise path if needed
if [[ ! "${output_path}" ]]; then
  output_path="${input_folder}"
fi
if [[ "${output_path%/*}" == "${output_path}" ]]; then
  output_path="${PWD}/${output_path}"
fi

if [[ -d "${output_path}" ]]; then
  if [[ "${suffix}" == '#' ]]; then
    if [[ "${output_path}" == "${output_path##*.}" ]]; then
      output_file="${output_path%.*}.${extension}"
    else
      output_file="${output_path}"
    fi
  else
    if [[ "${output_path}" == "${output_path##*.}" ]]; then
      output_file="${output_path%.*}${suffix}.${extension}"
    else
      output_file="${output_path%.*}${suffix}.${output_path##*.}"
    fi
  fi
elif [[ -f "${output_path}" ]]; then
  if [[ "${suffix}" == '#' ]]; then
    suffix=''
  fi
  output_file="${output_path%.*}_${output_path##*.}${suffix}.${extension}"
else
  output_file="${output_path}"
fi

verify_manifest "${output_file}"

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

# end log file
rm "${TMP_MANIFEST}"
echo "$(date_time) END" >> "${LOG_FILE}"
