#!/usr/bin/env bash

# Modify a BagIt archive, according to RFC 8493.
#
# 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}"
bagit_version="${bagit_version:-1.0}"
md5="${md5:-$(which md5sum)}"
sha1="${sha1:-$(which sha1sum)}"
sha256="${sha256:-$(which sha256sum)}"
sha512="${sha512:-$(which sha512sum)}"
crc32="${crc32:-$(which crc32)}"
xxh32="${xxh32:-$(which xxhsum) -H32}"
xxh64="${xxh64:-$(which xxhsum) -H64}"
xxh128="${xxh128:-$(which xxhsum) -H128}"

# initialise other default values
version_regex='^1.0|0.9[3-7]$'  # 1.0 and deprecated from 0.93 to 0.97
declare -a algorithm_list=('sha512' 'md5' 'sha1' 'sha256')
algorithm_list+=('crc32' 'xxh32' 'xxh64' 'xxh128')

# initialise variables
unset algorithm
unset input_path


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


# print an 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}"
  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
  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|-b) <input_folder> [-v <new_version>]
  ${SCRIPT_NAME} -h | -x
Options:
  -i  BagIt archive folder
  -b  is an alias of -i
  -v  new BagIt version
  -h  this help
  -x  advanced options with their default arguments
      (${tmp})
Default dependency:
  one of sha512sum, md5sum, sha1sum, sha256sum, xxhsum or crc32
See also:
  man ${SCRIPT_NAME}
  https://avpres.net/Bash_AVpres/
About:
  Abstract: Modify a BagIt archive of a folder, according to RFC 8493
  Version:  ${VERSION}

EOF
  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 options" >> "${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

Advanced options with their default arguments:
  --version='${bagit_version}'
  --md5='${md5}'
  --sha1='${sha1}'
  --sha256='${sha256}'
  --sha512='${sha512}'
  --crc32='${crc32}'
  --xxh32='${xxh32}'
  --xxh64='${xxh64}'
  --xxh128='${xxh128}'

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


# check that provided input folder is valid and normalise path if needed
# check that 'bagit.txt' file is present
check_input() {
  if [[ ! "${input_path}" ]]; then
    abort "Error: No input folder provided via '-i', '-b', '--input' or '--bagit'."
  elif [[ ! -d "${input_path}" ]]; then
    abort "Error: '${input_path}' is not a directory."
  fi
  if [[ "${input_path%/*}" == "${input_path}" ]]; then
    input_path="${PWD}/${input_path}"
  fi
  if [[ ! -f "${input_path}/bagit.txt" ]]; then
    abort "Error: The 'bagit.txt' file is missing."
  fi
}


# find algorithm and check that command is running
check_algorithm() {
  for algo in "${algorithm_list[@]}"; do
    if [[ -f "${input_path}/manifest-${algo}.txt" ]]; then
      algorithm="${algo}"
      break
    fi
  done
  if [[ ! "${algorithm}" ]]; then
    abort "Error: No 'manifest-<algorithm>.txt' file found."
  fi
  if [[ ! "${!algorithm}" ]]; then
    abort "Error: Cannot find '${algorithm}'."
  fi
  if ! command -v ${!algorithm} &> /dev/null; then
    abort "Error: '${algorithm}' is failing."
  fi
}


# check BagIt version
check_version() {
  if [[ ! $(echo "${bagit_version}" | grep -E "${version_regex}") ]]; then
    abort "Error: BagIt-Version '${bagit_version}' is not valid."
  fi
}


# modify BagIt archive
modify_bagit() {
  local tmp

  # modify the BagIt version in the 'bagit.txt' file
  echo "$(date_time) modify 'bagit.txt'" >> "${LOG_FILE}"
  sed -i.bak "s/^\(BagIt-Version: \).*/\1${bagit_version}/" \
    "${input_path}/bagit.txt"
  [[ -f "${input_path}/bagit.txt.bak" ]] && rm "${input_path}/bagit.txt.bak"

  # update 'tagmanifest-<algorithm>.txt' with the new checksum of 'bagit.txt'
  if [[ -f "${input_path}/tagmanifest-${algorithm}.txt" ]]; then
    tmp="$(${!algorithm} "${input_path}/bagit.txt" | awk '{print $1}')"
    sed -i.bak "s/^.*\(bagit.txt\)/${tmp}  \1/" \
      "${input_path}/tagmanifest-${algorithm}.txt"
    [[ -f "${input_path}/tagmanifest-${algorithm}.txt.bak" ]] \
      && rm "${input_path}/tagmanifest-${algorithm}.txt.bak"
  fi

  echo -e "${BLUE}The version has been updated.${NC}"
  echo "The version has been updated." >> "${LOG_FILE}"
}


# start log file
[[ -d '/tmp/AVpres' ]] || mkdir -p '/tmp/AVpres'
LOG_FILE="$(mktemp -q "/tmp/AVpres/${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

# parse and process provided input
(( $# == 0 )) && print_prompt
while getopts ":b:i:v:-:hx" opt; do
  case "${opt}" in
    b) if [[ "${OPTARG:0:1}" == '-' ]]; then
         abort "Error: The parameter '-b' requires an argument."
       else
         input_path="${OPTARG}"
       fi ;;
    i) if [[ "${OPTARG:0:1}" == '-' ]]; then
         abort "Error: The option '-i' requires an argument."
       else
         input_path="${OPTARG}"
       fi ;;
    v) if [[ "${OPTARG:0:1}" == '-' ]]; then
         abort "Error: The option '-v' requires an argument."
       else
         bagit_version="${OPTARG}"
       fi ;;
    -) case "${OPTARG}" in
         bagit=?*) input_path="${OPTARG#*=}" ;;
         input=?*) input_path="${OPTARG#*=}" ;;
         version=?*) bagit_version="${OPTARG#*=}" ;;
         md5=?*) md5="${OPTARG#*=}" ;;
         sha1=?*) sha1="${OPTARG#*=}" ;;
         sha256=?*) sha256="${OPTARG#*=}" ;;
         sha512=?*) sha512="${OPTARG#*=}" ;;
         crc32=?*) crc32="${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 input folder
check_input

# find algorithm and check that command is running
check_algorithm

# check BagIt version
check_version

# modify BagIt archive
modify_bagit

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