#!/bin/sh

set -e

if [ -z $ARCH ]; then
    ARCH='linux'
fi

if [ -z $MODE ]; then
    MODE='debug'
fi

case $ARCH in
  "linux")
      if [ -z $CC ]; then
          CC='gcc'
      fi
    ;;
  "web")
      CC=emcc
   ;;
esac

# setup dirs
SRC_DIR=./arch/$ARCH
BUILD_DIR=./out/$ARCH
GEN_DIR=$BUILD_DIR/gen
TOOL_SRC=tools/file2header.c
TOOL_EXE=$BUILD_DIR/file2header

# clean cmd
case $1 in
    "clean")
    echo "Deleting $BUILD_DIR"
    rm -rf $BUILD_DIR
    exit 0
esac

# create the build dir if it doesnt exist
if [ -d $BUILD_DIR ]; then
    echo "Building to $BUILD_DIR"
else
    echo "$BUILD_DIR not found, creating"
    mkdir -p $BUILD_DIR
fi

# Ensure gen dir exists
mkdir -p $GEN_DIR

# Check if tool source exists
if [ ! -f $TOOL_SRC ]; then
    echo "Error: $TOOL_SRC not found!"
    exit 1
fi

# Compile tool if exe missing or source changed
if [ ! -f $TOOL_EXE ] || [ $TOOL_SRC -nt $TOOL_EXE ]; then
    echo "Compiling file2header tool..."
    $CC $TOOL_SRC -o $TOOL_EXE
fi

# setup the build flags based on the build mode
case $MODE in
    "debug")
    BUILD_FLAGS="-g -Wall -Wextra -Werror -pedantic"
    ;;
    "release")
    BUILD_FLAGS="-O3 -Wall -Wextra -Werror -pedantic"
    ;;
esac

# build the core VM
VM_BUILD_FLAGS="$BUILD_FLAGS -std=c89 -ffreestanding -nostdlib -fno-builtin"
${CC} -c libc.c -o $BUILD_DIR/libc.o $VM_BUILD_FLAGS
${CC} -c list.c -o $BUILD_DIR/list.o $VM_BUILD_FLAGS
${CC} -c strbuf.c -o $BUILD_DIR/strbuf.o $VM_BUILD_FLAGS
${CC} -c lexer.c -o $BUILD_DIR/lexer.o $VM_BUILD_FLAGS
${CC} -c compiler.c -o $BUILD_DIR/compiler.o $VM_BUILD_FLAGS

# Set up the final build command
case $ARCH in
  "linux")
    BUILD_CMD="$CC -o $BUILD_DIR/undar $SRC_DIR/main.c emit/rer/emit.c emit/uxn/emit.c $LINK_FLAGS $BUILD_DIR/libc.o $BUILD_DIR/list.o $BUILD_DIR/lexer.o $BUILD_DIR/compiler.o $BUILD_DIR/strbuf.o $BUILD_FLAGS $LINK_FLAGS"
    ;;
  "web")
    BUILD_CMD="$CC $SRC_DIR/main.c emit/rer/emit.c emit/uxn/emit.c $BUILD_DIR/libc.o $BUILD_DIR/list.o $BUILD_DIR/lexer.o $BUILD_DIR/compiler.o -o $BUILD_DIR/undar.html $BUILD_FLAGS $LINK_FLAGS"
   ;;
esac

echo "$BUILD_CMD"
 ${BUILD_CMD}

echo "Finished building to $BUILD_DIR/undar"
