#!/bin/bash

# First, we will set up some colors to indicate status of notifications.
# Then we will set up a  basic help function that will be accessed several times.

green="\033[0;32m"		# Turn text green
red="\033[0;31m"		# Turn text red
nc="\033[0m"			# Turn off text colors

helpme() {
	echo ""
	echo -e "${green}checkmatch 'sha #' 'ISO file' 'sha file or hash code'${nc}"
	echo ""
	echo -e "${green}'sha #'${nc}"
	echo "    Use whatever number of sha you have."
	echo "Ex.: 256 for sha256sum"
	echo ""
	echo -e "${green}'ISO file'${nc}"
	echo "    Use in the second slot the full path and file name of your ISO"
	echo "    The file name must end with .iso"
	echo ""
	echo -e "${green}'sha file'${nc}"
	echo "    Use in the third slot the file name of the downloaded sha file, including the full path"
	echo "    if needed. The file name must include sha somewhere in its name."
	echo "    If the distro maintainers only gave you the hash number, you have two options:"
	echo "       1) You can use a text editor to copy the output they give you and paste it "
	echo "          into a new file. When you create the name for it, make sure 'sha' is"
	echo "          somewhere in the file name. Then enter it into the third slot"
	echo "      2)  You can alternately, copy just the hash code and paste it into the third"
	echo "          slot directly."
	echo ""
	sleep 10
}

# Now we will check the validity of the variables given at the command line.

# Check to make sure $1 is an integer and set up help flags ot display help text.

case $1 in
    -h | --help) helpme ; exit ;;
    ''|*[!0-9]*) echo -e "\n${red}The first data has a syntax issue . . .${nc}" ; helpme; exit ;;
    *) ;;
esac

# Now we check the iso file, to make sure it exists and is an iso file.
if [[ ! -f ${2} ]]; then
		echo -e "\n${red}The iso file does not exist . . .${nc}"
		helpme
		exit
elif [[ ${2} != *".iso"* ]] && [[ ${2} != *".ISO"* ]]; then
		echo -e "\n${red}The file isn't an ISO file . . .${nc}"
		helpme
		exit
fi

# And fianlly we will check the third entry to ensure whether it is a file or not and
#   if it is, we will check to make sure it is an sha file. If the entry does not
#   contain a ".", then  we will assume it it is a hash of the file.

if [[ -f ${3} ]]; then
	if [[ ${3} != *"sha"* ]]; then
		echo -e "\n${red}The third data entry is not an 'sha' file.${nc}" 
		helpme
		exit
	fi
	secondvar=$(cat ${3})
else
	if [[ ${3} == *"."* ]]; then
		echo -e "\n${red}This isn't a hash code or the sha file does not exist. Syntax error . . .${nc}"
		helpme
		exit
	fi
	secondvar=${3}
fi

# Now we process the hashes to see whether they match or not.

firstvar=$(sha${1}sum ${2})
IFS=' ' read -ra checknum <<< "${firstvar}"

if [[ $secondvar == *"${checknum[0]}"* ]]; then
	echo -e "\n${green}CONGRADULATIONS! The hash codes MATCH!${nc}\n"
else
	echo -e "\n${red}The hash codes DO NOT match.${nc}\n"
fi

