#!/bin/bash
final_dir="${HOME}/Downloads/switch/game-dumps/final"

nsp_dir=$1
if [[ $nsp_dir == '' ]]; then
	nsp_dir="."
fi

function combine_nsp_parts {
	big_nsp_dir=$1
	echo "Multipart NSP found, combining ${big_nsp_dir}"
	declare -i total_size=0
	for fname in "$big_nsp_dir/"*
	do
		current_file_size=$(stat -c%s "$fname")
		let total_size=$total_size+$current_file_size
	done
	mv "$big_nsp_dir" "${big_nsp_dir}.d"
	cat "./${big_nsp_dir}.d"/* | pv -epts ${total_size} > "${nsp_dir}${big_nsp_dir}"
	echo "Done."
}
export -f combine_nsp_parts

echo "Checking for multipart nsps."
find "$nsp_dir" -name "*.nsp" -type d -exec bash -c 'combine_nsp_parts "$0"' {} \;

echo "Renaming nsps."
# TODO: Try and make this less clunky and directory independent.
find "$nsp_dir" -name "*.nsp" -exec rename '(' '[' {} \;
find "$nsp_dir" -name "*.nsp" -exec rename ')' ']' {} \;

echo "Compressing and moving nsps."
mkdir -p "$final_dir"
find "$nsp_dir" -name "*.nsp" -exec nsz -Cp {} +
# TODO: Try and make this less clunky and directory independent.
find "$nsp_dir" -name "*.nsz" -exec mv {} "$final_dir/" \;
