#!/bin/bash

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

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

# set these false at the start to be safe
checksha256=false
checkmd5=false

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

# environment checks
## check for presence of $sha256_file_path, fail with general error on error
if [ ! -f "$sha256_file_path" ]; then
    echo -e "\n${RED}FAIL!${RESET} File $sha256_file_path Not Found!\n" >&2
    exit 1 
fi
## check if $sha256_file_path is writable
if [ ! -r "$sha256_file_path" ]; then
    echo -e "\n${RED}FAIL!${RESET} File $sha256_file_path Exists But Not Readable!\n" >&2
    exit 1
fi
## check for presence of $md5_file_path, fail with general error on error
if [ ! -f "$md5_file_path" ]; then 
    echo -e "\nFAIL! File $md5_file_path Not Found!\n" >&2
    exit 1
fi
## check if $md5_file_path is writable
if [ ! -r "$md5_file_path" ]; then
    echo -e "\n${RED}FAIL!${RESET} File $md5_file_path Exists But Not Readable!\n" >&2
    exit 1
fi

# check checksums
## check sha256
if sha256sum -c "$sha256_file_path" 1>/dev/null; then
    echo -e "SHA256 Checksums: ${GREEN}OK!${RESET}"
    checksha256=true
else
    echo -e "\n\nSHA256 Checksums: ${RED}BAD!${RESET}\nDumping SHA256 Checksum Fails:" >&2
    sha256sum -c "$sha256_file_path" | grep 'FAILED' >&2
    echo -e "\nSHA256 Checksums: ${RED}BAD!${RESET}\n" >&2
fi
## check md5
if md5sum -c "$md5_file_path" 1>/dev/null; then
    echo -e "MD5 checksums: ${GREEN}OK!${RESET}"
    checkmd5=true
else
    echo -e "\n\nFAIL: MD5 Checksums: ${RED}BAD!${RESET}\n\tDumping MD5 Checksum Fails:" >&2
    md5sum -c "md5_file_path" | grep 'FAILED' >&2
    echo -e "\nMD5 Checksums: ${RED}BAD!${RESET}\n" >&2
fi

# tally checks
if [[ $checksha256 == true && $checkmd5 == true ]]; then
    echo -e "\nFile Integrity: VERIFIED! All Checksums: ${GREEN}OK!${RESET}\n"
    exit 0 # exit success
else
    echo -e "\nFile Integrity Check: ${RED}FAILED!${RESET}\n\tSee Above or See $error_log" >&2
    exit 1 # exit general failure
fi