#!/usr/bin/env bash

# Test some cryptographic and non-cryptographic checksum algorithm tools on a
# computer.
#
# Copyright (c) 2020-2022 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.


# prompt a help menu or set the value to use for the checksum computing
if [[ "${1}" == "-h" ]]; then
  cat << EOF

Usage:
  $(basename "$0") [string]
  $(basename "$0") -h

Arguments:
  string  if a string is passed, then its checksums are computed; otherwise
          the checksums of the current timestamp are computed
  -h      this help

EOF
  exit 0
else
  TMP="${1:-$(date)}"
fi

# compute the checksum for several algorithms and prompt the result
# 'cksum' generates a decimal checksum which is converted to hex
echo
printf '%10s   %-s\n' "Algorithm" "Checksum"
printf '%64s\n' | tr " " "-"
printf '%10s = %-s\n' "SHA-512" "$(sha512sum <(echo "${TMP}") 2>/dev/null | awk '{print $1}')"
printf '%10s = %-s\n' "SHA-256" "$(sha256sum <(echo "${TMP}") 2>/dev/null | awk '{print $1}')"
printf '%10s = %-s\n' "SHA-1" "$(sha1sum <(echo "${TMP}") 2>/dev/null | awk '{print $1}')"
printf '%10s = %-s\n' "MD5" "$(md5sum <(echo "${TMP}") 2>/dev/null | awk '{print $1}')"
printf '%10s = %-s\n' "xxHash 128" "$(xxhsum -H128 <(echo "${TMP}") 2>/dev/null | awk '{print $1}')"
printf '%10s = %-s\n' "xxHash 64" "$(xxhsum -H64 <(echo "${TMP}") 2>/dev/null | awk '{print $1}')"
printf '%10s = %-s\n' "xxHash 32" "$(xxhsum -H32 <(echo "${TMP}") 2>/dev/null | awk '{print $1}')"
printf '%10s = %-x\n' "CRC-32" "$(cksum <(echo "${TMP}") 2>/dev/null | awk '{print $1}')"
printf '%64s\n' | tr " " "-"
echo
