#!/bin/zsh
datestamp=$(date "+%d%m%y%H%M%S")
chip="esp32s3"
file_prefix=$1
out_dir="./live-roms/$file_prefix-$datestamp"
no_stub=True # True/False case sensitive
args_file="./args_file.txt"
log_file="$out_dir/log.txt"
tmp_file="./.dump_rom_tmp.tmp"
start_header="Starting dump from chip: $chip\n	on port: $ESPPORT\n	at: $ESPBAUD baud\n	to directory: $out_dir\n	with log file: $log_file\n"

mkdir $out_dir

if [ "$no_stub" != "False" ]; then
	stubby='--no-stub'
fi


echo "\n====================="
echo $start_header

echo $start_header >> $log_file

# usage dump_section name bus start end
# start and end are hex values in bytes beginning with 0x
# name and bus are strings with no spaces
dump_section () {
	dump_length=0x$(([##16] $4 - $3))
	file_name="$out_dir/$file_prefix-$chip-$1-$2-$3-$4-$dump_length-$datestamp.bin"
	command="esptool.py \ \n	$stubby --baud $ESPBAUD \ \n	--port $ESPPORT \ \n	--chip $chip \ \n	dump_mem $3 $dump_length \ \n	$file_name"

	header="$1\n	on $2\n 	starting: $3\n	ending: $4\n	length: $dump_length\n	on $chip\n	no_stub: $no_stub\n\nRunning: $command"

	echo "\nDumping Section:\n$header\n\nPlease wait..."

	echo $header >> $log_file
	echo "	File: $file_name" >> $log_file
	echo "	$command" >> $log_file

	esptool.py `echo $stubby` --baud $ESPBAUD --port $ESPPORT --chip $chip dump_mem $3 $dump_length $file_name > $tmp_file
	return_status=$?

	if [ $return_status -ne 0 ]; then
		echo "	ERROR: return status $return_status dump:" >> $log_file
		cat $tmp_file >> $log_file
		echo "ERROR: dump failed. check $log_file"
		echo "esptool output:"
		cat $tmp_file
		rm $tmp_file
		exit
	fi

	checksum=$(sha256sum $file_name)
	echo "	sha256sum: $checksum" >> $log_file
	echo "	Sucess\n===\n" >> $log_file
	echo "Successfully dumped\nsha256sum: $checksum\n continuing..."
}


for args in ${(f)"$(<$args_file)"};
do
	dump_section `echo $args`
done

sha256sum $out_dir/* >> $out_dir/sha256sum.txt

echo "\nDone :3"
