trap "exit 1" INT

fail() { echo "❌ $1"; exit 1; }

if [ $# -lt 1 ]; then
  fail "Usage: $0 <backend> --shell shell -m pattern --bootstrap" 1
fi

# Parse the arguments
# : ${PNUT_OPTIONS:=} # Default to empty options
# backend=$1; shift
# bootstrap=0
# safe=0
# fast=0
# one_pass=0
# compile_only=0
# create_golden_file=1 # Create golden files by default
# shell="$SHELL" # Use current shell as the default
# pattern=".*"
# shellcheck disable=SC2034

while [ "$#" -gt 0 ]; do
  case $1 in
    --shell)                  shell="$2";         shift 2;;
    --match)                  pattern="$2";       shift 2;;
    --bootstrap)              bootstrap=1;        shift 1;;
    --safe)                   safe=1;             shift 1;;
    --fast)                   fast=1;             shift 1;;
    --one-pass-generator)     one_pass=1;         shift 1;;
    --compile-only)           compile_only=1;     shift 1;;
    --no-create-golden-file)  create_golden_file=0;     shift 1;;
    *) echo "Unknown option: $1"; exit 1;;
  esac
done

# shellcheck disable=SC2034,SC2154

# determine the file extension based on the backend
case "${backend}" in
  sh)
    ext="exe" # The extension doesn't matter for sh
    PNUT_EXE_OPTIONS="${PNUT_OPTIONS} -Dsh -DRT_NO_INIT_GLOBALS"
    ;;
  i386_linux | x86_64_linux | x86_64_mac)
    ext="exe"
    PNUT_EXE_OPTIONS="${PNUT_OPTIONS} -Dtarget_${backend}"
    ;;
  *)
    echo "Unknown backend: ${backend}"
    exit 1
    ;;
esac

if [ "${safe}" -eq 1 ]; then
  # Enable safe mode which checks get_child accesses
  PNUT_EXE_OPTIONS="${PNUT_EXE_OPTIONS} -DSAFE_MODE"
fi

if [ "${fast}" -eq 1 ]; then
  if [ "${backend}" != "sh" ]; then
    fail "Fast mode is not supported for the sh backend"
  fi
  # Enable fast mode which uses a faster implementation for local variables
  PNUT_EXE_OPTIONS="${PNUT_EXE_OPTIONS} -DSH_SAVE_VARS_WITH_SET"
fi

if [ "${one_pass}" -eq 1 ]; then
  # Enable the one pass mode for pnut-exe's code generator
  PNUT_EXE_OPTIONS="${PNUT_EXE_OPTIONS} -DONE_PASS_GENERATOR"
fi
