#!/bin/bash
set -x

# Function to check if a directory exists and create it if not
ensure_directory_exists() {
	local dir_path="$1"
	local output_file="$2"

	echo "*** adding mkdir -p $dir_path to the conf_print file"
	echo -e "\nmkdir -p debian/$(basename $dir_path)\n" >>"$output_file"

	echo "calling generate_functions() on $dir_path"
	generate_functions "$dir_path" "$output_file"
}

# Function to generate functions for text files in a directory
generate_functions() {
	local directory=$1
	local output_file=$2

	for item in "$directory"/*; do
		if [ -d "$item" ]; then
			# If the item is a directory, recursively call generate_functions on it
			ensure_directory_exists "$item" "$output_file"
		elif [ -f "$item" ]; then
			# If the item is a file, proceed with generating functions as before
			local filename=$(basename "$item" .txt)
			local function_name="conf_print_$(echo "$filename" | tr -c '[:alnum:]' '_')"

			local heredoc=$(
				cat <<-FOE

					$function_name() {
					cat <<-'EOF'
					$(cat "$item")
					EOF
					}
				FOE
			)
			echo "$heredoc" >>"$output_file"
			echo "# $function_name | tee $directory/$filename >/dev/null" >>"$output_file"
		fi
	done
}

# Main script execution
if [ "$#" -ne 2 ]; then
	echo "Usage: $0 <directory> <output_file>"
	exit 1
fi

directory=$1
output_file=$2

# Generate functions for the directory
generate_functions "$directory" "$output_file"

echo "Functions generated and appended to $output_file"
