#!/bin/bash
cd -- "$(dirname -- "${BASH_SOURCE[0]}")"

if [ ! -x "bin/slunkcrypt-a" ]; then
	echo "Executbale file \"bin/slunkcrypt-a\" not found !!!"
	exit 1
fi
if [ ! -x "bin/slunkcrypt-b" ]; then
	echo "Executbale file \"bin/slunkcrypt-b\" not found !!!"
	exit 1
fi

rm -rf "org" "enc" "out"
mkdir -p "bin" "org" "enc" "out"

readonly PASSWD=("T25na1i{XYuUMFDi2fRqk258" "dq22Z.[[>C9zml#n)<e)vFkG")

# Generate input files
echo -e "\n\033[1;36m---===[ generate input ]===---\033[0m\n"
for i in 1 13 31 89 223 503 997 2477 5003 9973 24989 50021 99991 249989 500009 999983 134217757; do
	echo "Generating \"$(printf "%07X" ${i}).bin\" please wait..."
	dd if="/dev/urandom" of="org/$(printf "%07X" ${i}).bin" bs=1 count=${i}
	for j in {1..7}; do
		echo "Generating \"$(printf "%07X" $(($i + $j))).bin\" please wait..."
		cp -f "org/$(printf "%07X" ${i}).bin" "org/$(printf "%07X" $(($i + $j))).bin"
		dd oflag=append conv=notrunc if="/dev/urandom" of="org/$(printf "%07X" $(($i + $j))).bin" bs=1 count=${j}
	done
done

for file in org/*; do
	name="$(basename -- "$file")"
	echo -e "\n\033[1;36m---===[ ${name} ]===---\033[0m\n"

	# Encrypt -A-
	for i in {0..1}; do
		if ! ${BASH} -x -c "bin/slunkcrypt-a -e \"pass:${PASSWD[$i]}\" \"${file}\" \"enc/${name}~~A${i}\""; then
			echo -e "\n\033[1;31mError: File could not be encoded !!!\033[0m"
			exit 1
		fi
	done

	# Encrypt -B-
	for i in {0..1}; do
		if ! ${BASH} -x -c "bin/slunkcrypt-b -e \"pass:${PASSWD[$i]}\" \"${file}\" \"enc/${name}~~B${i}\""; then
			echo -e "\n\033[1;31mError: File could not be encoded !!!\033[0m"
			exit 1
		fi
	done

	# Print hash
	sha256sum "enc/${name}~~"* && echo ""

	# Decrypt -A/B-
	for i in {0..1}; do
		if ! ${BASH} -x -c "bin/slunkcrypt-a -d \"pass:${PASSWD[$i]}\" \"enc/${name}~~B${i}\" \"out/${name}~~A${i}\""; then
			echo -e "\n\033[1;31mError: File could not be decoded !!!\033[0m"
			exit 1
		fi
		if ! cmp "out/${name}~~A${i}" "${file}"; then
			echo -e "\n\033[1;31mError: Decoded file does *not* match original !!!\033[0m"
			exit 1
		fi
	done

	# Decrypt -B/A-
	for i in {0..1}; do
		if ! ${BASH} -x -c "bin/slunkcrypt-b -d \"pass:${PASSWD[$i]}\" \"enc/${name}~~A${i}\" \"out/${name}~~B${i}\""; then
			echo -e "\n\033[1;31mError: File could not be decoded !!!\033[0m"
			exit
		fi
		if ! cmp "out/${name}~~A${i}" "out/${name}~~B${i}"; then
			echo -e "\n\033[1;31mError: Decoded files are *not* the same !!!\033[0m"
			exit 1
		fi
	done

	# Print hash
	sha256sum "out/${name}~~"* && echo ""
done

echo -e "\n\033[1;32mAll tests have completed successfully!\033[0m"
