#!/usr/bin/env bash
# x-sha256sum-matcher
#
# Check if two files are the same
#
# Ismo Vuorinen <https://github.com/ivuorinen> 2023
# MIT License

# ENV Variables
: "${VERBOSE:=0}" # VERBOSE=1 x-sha256sum-matcher file1 file2

file_1="$1"
file_2="$2"

# return sha256sum for file
# $1 - filename (string)
get_sha256sum()
{
  sha256sum "$1" | head -c 64
}

[ $# -eq 0 ] && {
  echo "Usage: $0 file1.sh file2.sh" && exit 1
}

msg()
{
  [[ "$VERBOSE" -eq 1 ]] && echo "$1"
}

error()
{
  msg "(!) ERROR: $1" && exit 1
}

if [ ! -f "$file_1" ]; then
  error "File 1 does not exist: $file_1"
fi

if [ ! -f "$file_2" ]; then
  error "File 2 does not exist: $file_2"
fi

file_1_hash=$(get_sha256sum "$file_1")
file_2_hash=$(get_sha256sum "$file_2")

if [ "$file_1_hash" != "$file_2_hash" ]; then
  error "Files do not match"
else
  msg "(*) Success: Files do match"
  exit 0
fi
