#!/bin/sh

# This "enchant" spell imbues a file with the power of its own hash, binding it to its own unique identity.
# The spell requires a single argument: the path to the file to be enchanted.
# The resulting CRC-32 hash is saved as an extended attribute called "user.hash" in hexadecimal.

# Check if the required argument was provided
if [ -z "$1" ]; then
  # If no argument was given, display an error message and exit
  echo "Error: No file specified."
  exit 1
fi

# Set the path to the file
file="$1"

# Check if the file exists
if [ ! -e "$file" ]; then
  # If the file does not exist, display an error message and exit
  echo "Error: File not found."
  exit 1
fi

# Calculate the hash of the file
hash=$(echo -n "$file" | cksum | awk '{ print "0x"$1 }')

# Save the hash as an extended attribute
if command -v attr > /dev/null; then
  attr -s "hash" -V "$hash" "$file" 2>&1 >/dev/null
elif command -v xattr > /dev/null; then
  xattr -w "user.hash" "$hash" "$file" 2>&1 >/dev/null
elif command -v setfattr > /dev/null; then
  setfattr -n "user.hash" -v "$hash" "$file" 2>&1 > /dev/null
else
  # If neither xattr or attr is available, display an error message and exit
  echo "Error: xattr and attr commands not found. Cannot enchant file."
  exit 1
fi

echo "File enchanted with hash: $hash"