#!/bin/bash

# --- export_step.sh ---
# Converts an OpenSCAD file to a STEP file using FreeCAD.
#
# !! REQUIRES FREECAD !!
# This script depends on FreeCAD being installed and 'FreeCADCmd.exe'
# being available in your system's PATH.
#
# Usage: ./export_step.sh <source.scad> [output.step]
#
# Arguments:
#   $1: source_file  - Input .scad file (Required)
#   $2: output_file  - Output .step file (Optional)

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

# --- Argument Parsing ---
SOURCE_FILE="$1"
OUTPUT_FILE="$2"

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

# --- Define Temporary STL file ---
TEMP_STL_FILE="temp_conversion.stl"

# --- Step 1: Export from OpenSCAD to STL ---
echo "Step 1/3: Exporting '$SOURCE_FILE' to STL using dedicated export layout..."
openscad \
    -o "$TEMP_STL_FILE" \
    -D "view_mode=\"export\"" \
    "$SOURCE_FILE"

if [ $? -ne 0 ]; then
    echo "Error: OpenSCAD export failed."
    exit 1
fi
echo "STL export successful."

# --- Step 2: Convert STL to STEP using FreeCAD ---
echo "Step 2/3: Converting '$TEMP_STL_FILE' to '$OUTPUT_FILE' using FreeCAD..."
# Note: Assuming FreeCADCmd.exe for Windows. Use 'freecadcmd' on Linux.
FreeCADCmd.exe -c converter.py "$TEMP_STL_FILE" "$OUTPUT_FILE"

if [ $? -ne 0 ]; then
    echo "Error: FreeCAD conversion failed. Is FreeCAD installed and in your PATH?"
    rm -f "$TEMP_STL_FILE" # Clean up temp file
    exit 1
fi
echo "STEP conversion successful."

# --- Step 3: Clean up temporary files ---
echo "Step 3/3: Cleaning up temporary files..."
rm -f "$TEMP_STL_FILE"
echo "Done."

# --- Completion Message ---
echo "Export complete: '$OUTPUT_FILE' created successfully." 