#!/bin/bash

# --- generate_cut_plan.sh ---
# Generates a markdown cut plan from an OpenSCAD file.
# This script calls OpenSCAD in a special mode to echo the plan.
#
# Usage: ./generate_cut_plan.sh <source.scad> [output.md]
# If output file is not provided, prints to console.

# --- Input Validation ---
if [ -z "$1" ]; then
    echo "Usage: $0 <source.scad> [output.md]"
    echo "Error: Source file not specified."
    exit 1
fi

SOURCE_FILE="$1"
OUTPUT_FILE="$2"
DUMMY_OUTPUT="cutplan_dummy.stl" # A dummy file to force command-line execution

# --- OpenSCAD Command ---
# We force a dummy output file with -o to prevent the GUI from launching.
# OpenSCAD prints echo() statements to stderr. We redirect stderr to stdout (2>&1), 
# then use grep to filter for only the lines starting with "ECHO:", 
# and then use sed to remove the prefix and surrounding quotes for a clean output.
CUTPLAN_CONTENT=$(openscad \
    -o "$DUMMY_OUTPUT" \
    -D "view_mode=\"cutplan\"" \
    "$SOURCE_FILE" \
    2>&1 | grep "ECHO:" | sed 's/ECHO: "//;s/"$//')

# Check the exit status of the openscad command.
if [ ${PIPESTATUS[0]} -ne 0 ]; then
    echo ""
    echo "Error: OpenSCAD command failed."
    rm -f "$DUMMY_OUTPUT" # Clean up dummy file on failure
    exit 1
fi

# Clean up the dummy file
rm -f "$DUMMY_OUTPUT"

# --- Output the result ---
if [ -z "$OUTPUT_FILE" ]; then
    echo ""
    echo "--- Generated Cut Plan (Markdown) ---"
    echo "$CUTPLAN_CONTENT"
    echo "-------------------------------------"
else
    echo "$CUTPLAN_CONTENT" > "$OUTPUT_FILE"
    echo "Cut plan successfully saved to '$OUTPUT_FILE'."
fi 