#!/bin/bash
# file paths
sha256_file_path=./checksums.sha256
md5_file_path=./checksums.md5
error_log=./checksums_error.log

# text colors
RED='\e[31m'
YELLOW='\033[33m'
GREEN='\e[32m'
RESET='\e[0m'

# output errors to error log
exec 2> >(tee -a "$error_log" >&2)

if [ -f "sha256_file_path" ]; then
    echo -e "${YELLOW}Warn${RESET}: Existing $sha256_file_path Found, Deleting..."
    rm -f "sha256_file_path"
fi

if [ -f "$md5_file_path" ]; then
    echo -e "${YELLOW}Warn${RESET}: Existing $md5_file_path Found, Deleting..."
    rm -f "$md5_file_path"
fi

if [ -f "$error_log" ]; then
    echo -e "${YELLOW}Warn${RESET}: Existing $error_log Found, Deleting..."
    rm -f "$error_log"
fi

# notify user
echo "Calculating SHA256 and MD5 Checksums Recursively into $sha256_file_path and $md5_file_path\n\t${YELLOW}This May Take a Long Time!${RESET}"
# exclude git
if find . -type f ! -path "*/.git/*" ! -path "$error_log" ! -path "$md5_file_path" ! -path "$sha256_file_path" ! -path "$0" ! -path "./check_checksums.sh" -exec bash -c "file_path={} && sha256sum \$file_path 1>> $sha256_file_path && md5sum \$file_path 1>> $md5_file_path" \;; then
    echo -e "\n${GREEN}SUCCESS!${RESET} Generated SHA256 and MD5 Checksums into $sha256_file_path and $md5_file_path Respectively!\n"
    exit 0 # explicitly exit success
else
    echo -e "\n${RED}FAIL!${RESET} Failed to Generate SHA256 and MD5 Checksums! Check Error Output or Check Error Log: $error_log\n" >&2
    exit 1 # explicitly fail
fi