#!/bin/bash
TARGET=${1:-~/dev/.target}
mkdir -p "$TARGET"
# Inject constants
ENV_FILE=${ENV_FILE:-.env}
GEN_DIR="src/main/generated-sources"
if [ -f "$ENV_FILE" ]; then
    echo "Injecting constants from $ENV_FILE..."
    # Create Config.java from template
    mkdir -p "$GEN_DIR/puzzle"
    sed "s/\${CLUE_SIZE}/$(grep '^CLUE_SIZE=' "$ENV_FILE" | cut -d= -f2)/g;
         s/\${MIN_LEN}/$(grep '^MIN_LEN=' "$ENV_FILE" | cut -d= -f2)/g;
         s/\${MAX_TRIES_PER_SLOT}/$(grep '^MAX_TRIES_PER_SLOT=' "$ENV_FILE" | cut -d= -f2)/g;
         s/\${MAX_LEN}/$(grep '^MAX_LEN=' "$ENV_FILE" | cut -d= -f2)/g;
         s/\${PUZZLE_ROWS}/$(grep '^PUZZLE_ROWS=' "$ENV_FILE" | cut -d= -f2)/g;
         s/\${PUZZLE_COLS}/$(grep '^PUZZLE_COLS=' "$ENV_FILE" | cut -d= -f2)/g" \
         src/main/java-templates/puzzle/Config.java > "$GEN_DIR/puzzle/Config.java"
elif [ -f pom.xml ]; then
    echo "Injecting constants from pom.xml..."
    # Create Config.java from template
    mkdir -p "$GEN_DIR/puzzle"
    sed "s/\${CLUE_SIZE}/$(grep '<CLUE_SIZE>' pom.xml | sed 's/.*>\(.*\)<.*/\1/')/g;
         s/\${MIN_LEN}/$(grep '<MIN_LEN>' pom.xml | sed 's/.*>\(.*\)<.*/\1/')/g;
         s/\${MAX_TRIES_PER_SLOT}/$(grep '<MAX_TRIES_PER_SLOT>' pom.xml | sed 's/.*>\(.*\)<.*/\1/')/g;
         s/\${MAX_LEN}/$(grep '<MAX_LEN>' pom.xml | sed 's/.*>\(.*\)<.*/\1/')/g;
         s/\${PUZZLE_ROWS}/$(grep '<PUZZLE_ROWS>' pom.xml | sed 's/.*>\(.*\)<.*/\1/')/g;
         s/\${PUZZLE_COLS}/$(grep '<PUZZLE_COLS>' pom.xml | sed 's/.*>\(.*\)<.*/\1/')/g" \
         src/main/java-templates/puzzle/Config.java > "$GEN_DIR/puzzle/Config.java"
fi

javac -cp src/main/java/puzzle/postgresql-42.7.8.jar:$(find . -name "lombok-*.jar") -d "$TARGET" src/main/java/puzzle/*.java "$GEN_DIR/puzzle/Config.java"
