#!/bin/bash

# Check if at least one argument is provided
if [ "$#" -ne 1 ]; then
  echo "Usage: $0 <output_directory>"
  exit 1
fi

# Assign the first argument as the output directory
OUTPUT_DIR="$1"

# Ensure the output directory exists or try to create it
if [ ! -d "$OUTPUT_DIR" ]; then
  mkdir -p "$OUTPUT_DIR"
  if [ $? -ne 0 ]; then
    echo "Failed to create output directory: $OUTPUT_DIR"
    exit 2
  fi
fi

# Directory containing config files
CONFIG_DIR="data/configs/"

# Check if the config directory exists
if [ ! -d "$CONFIG_DIR" ]; then
  echo "Configuration directory does not exist: $CONFIG_DIR"
  exit 3
fi

# Iterate over each .toml file in the config directory
for config_file in "$CONFIG_DIR"*.toml; do
  # Check if config files are present
  if [ ! -f "$config_file" ]; then
    echo "No .toml config files found in $CONFIG_DIR"
    exit 4
  fi

  # Extract the filename without the extension
  base_name=$(basename -- "$config_file" .toml)

  # Execute the cargo command with the current config file and redirect the output
  echo "Processing $config_file..."
  cargo r -r -- -c "$config_file" > "$OUTPUT_DIR/$base_name.md"
done

echo "All configurations processed successfully."
