#!/bin/bash

# --- render.sh ---
# Renders an OpenSCAD file to a PNG image.
#
# Usage: ./render.sh <source_file.scad> [output_file.png] [folded_state]
#
# Arguments:
#   $1: source_file  - The path to the input OpenSCAD file. (Required)
#   $2: output_file  - The path for the output PNG image. (Optional)
#   $3: folded_state - 'true' or 'false' to control the Folded_View parameter.
#                      (Optional, defaults to false)

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

# --- Argument Parsing ---
SOURCE_FILE="$1"
OUTPUT_FILE=""
FOLDED_STATE="false" # Default value

# 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
    # Removes the .scad extension and appends .png
    OUTPUT_FILE="${SOURCE_FILE%.scad}_${FOLDED_STATE}.png"
fi

# --- OpenSCAD Render Command ---
# --view=iso: Sets the camera to a standard isometric view.
# --imgsize: Sets the output image resolution.
# -D: Overrides a variable in the OpenSCAD script.
echo "Rendering '$SOURCE_FILE' to '$OUTPUT_FILE' with Folded_View=$FOLDED_STATE..."
openscad \
    -o "$OUTPUT_FILE" \
    --view=iso \
    --imgsize=1024,768 \
    -D "Folded_View=$FOLDED_STATE" \
    "$SOURCE_FILE"

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