#!/usr/bin/env bash
#
# x-sha256sum-matcher
#
# Compare two files by computing their SHA256 hashes.
#
# Ismo Vuorinen <https://github.com/ivuorinen> 2023
# MIT License

set -euo pipefail

# Default settings
VERBOSE=0

# Print usage/help message
usage()
{
  cat << EOF
Usage: $0 [options] file1 file2

Compare two files by computing their SHA256 hashes.

Options:
  -v          Enable verbose output.
  -h, --help  Display this help message and exit.
EOF
}

# Check if a command exists
command_exists()
{
  command -v "$1" > /dev/null 2>&1
}

# Ensure sha256sum is available
if ! command_exists sha256sum; then
  echo "Error: sha256sum command not found. Please install it." >&2
  exit 1
fi

# Process command-line options
while [[ $# -gt 0 ]]; do
  case "$1" in
    -h | --help)
      usage
      exit 0
      ;;
    -v)
      VERBOSE=1
      shift
      ;;
    -*)
      echo "Error: Unknown option: $1" >&2
      usage
      exit 1
      ;;
    *)
      break
      ;;
  esac
done

# Validate input arguments: expect exactly 2 files
if [[ $# -ne 2 ]]; then
  echo "Error: Two file arguments required." >&2
  usage
  exit 1
fi

file1="$1"
file2="$2"

# Check if files exist and are readable
for file in "$file1" "$file2"; do
  if [[ ! -f "$file" ]]; then
    echo "Error: File does not exist: $file" >&2
    exit 1
  elif [[ ! -r "$file" ]]; then
    echo "Error: File is not readable: $file" >&2
    exit 1
  fi
done

# Print verbose messages if enabled
msg()
{
  if [[ "$VERBOSE" -eq 1 ]]; then
    echo "$1"
  fi
}

# Compute SHA256 hash for a file using awk to extract the first field
get_sha256sum()
{
  sha256sum "$1" | awk '{print $1}'
}

msg "Computing SHA256 for '$file1'..."
hash1=$(get_sha256sum "$file1")
msg "SHA256 for '$file1': $hash1"

msg "Computing SHA256 for '$file2'..."
hash2=$(get_sha256sum "$file2")
msg "SHA256 for '$file2': $hash2"

if [[ "$hash1" != "$hash2" ]]; then
  echo "Files do not match." >&2
  exit 1
else
  msg "Success: Files match."
  exit 0
fi
