#!/bin/bash

# --- export_stl.sh ---
# Exports an OpenSCAD file to an STL file.
#
# Usage: ./export_stl.sh <source.scad> [output.stl] [folded_state]
#
# Arguments:
#   $1: source_file  - Input .scad file (Required)
#   $2: output_file  - Output .stl file (Optional)
#   $3: folded_state - 'true' or 'false'. (Optional, defaults to 'true' for a solid model)

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

# --- Argument Parsing ---
SOURCE_FILE="$1"
OUTPUT_FILE=""
# Default to 'true' as we usually want to export the assembled solid model
FOLDED_STATE="true" 

# Case 1: All three arguments are provided
if [ -n "$3" ]; then
    OUTPUT_FILE="$2"
    FOLDED_STATE="$3"
# Case 2: Only two arguments are provided
elif [ -n "$2" ]; then
    # Check if the second argument is the folded state or a filename
    if [[ "$2" == "true" || "$2" == "false" ]]; then
        FOLDED_STATE="$2"
    else
        OUTPUT_FILE="$2"
    fi
fi

# --- Set Default Output Filename ---
if [ -z "$OUTPUT_FILE" ]; then
    OUTPUT_FILE="${SOURCE_FILE%.scad}_${FOLDED_STATE}.stl"
fi

# --- OpenSCAD Export Command ---
# -D: Overrides a variable in the OpenSCAD script.
echo "Exporting '$SOURCE_FILE' to '$OUTPUT_FILE' with Folded_View=$FOLDED_STATE..."
openscad \
    -o "$OUTPUT_FILE" \
    -D "Folded_View=$FOLDED_STATE" \
    "$SOURCE_FILE"

# --- Completion Message ---
if [ $? -eq 0 ]; then
    echo "Export complete: '$OUTPUT_FILE' created successfully."
else
    echo "Error: OpenSCAD export failed."
    exit 1
fi 