#!/usr/bin/env bash

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
BIN_PATH="$PROJECT_DIR/target/release/thesa"

if [ "$#" -lt 1 ]; then
  echo "Usage: $0 <target> [output-root] [concurrency] [extra thesa flags excluding --output]"
  exit 1
fi

TARGET="$1"
OUTPUT_ROOT="${2:-$PROJECT_DIR/archives}"
CONCURRENCY="${3:-4}"

if [ "$#" -ge 4 ]; then
  shift 3
  EXTRA_ARGS=("$@")
else
  EXTRA_ARGS=()
fi

TARGET_SLUG="${TARGET}"
TARGET_SLUG="${TARGET_SLUG#https://github.com/}"
TARGET_SLUG="${TARGET_SLUG#http://github.com/}"
TARGET_SLUG="${TARGET_SLUG#git@github.com:}"
TARGET_SLUG="${TARGET_SLUG%.git}"
if [[ "$TARGET_SLUG" == *"/"* ]]; then
  TARGET_SLUG="${TARGET_SLUG##*/}"
fi

TARGET_SLUG="${TARGET_SLUG%/}"
TARGET_SLUG="${TARGET_SLUG#./}"

if [ -z "$TARGET_SLUG" ]; then
  echo "Invalid target: $TARGET"
  exit 1
fi

OUTPUT_DIR="$OUTPUT_ROOT/$TARGET_SLUG"
mkdir -p "$OUTPUT_DIR"

cd "$PROJECT_DIR"

if [ ! -x "$BIN_PATH" ] || [ "$PROJECT_DIR/Cargo.toml" -nt "$BIN_PATH" ] || [ "$PROJECT_DIR/Cargo.lock" -nt "$BIN_PATH" ] || [ "$PROJECT_DIR/src/main.rs" -nt "$BIN_PATH" ] ; then
  "$SCRIPT_DIR/compile.sh"
fi

FILTERED_ARGS=()
if [ "${#EXTRA_ARGS[@]}" -gt 0 ]; then
  while [[ "${#EXTRA_ARGS[@]}" -gt 0 ]]; do
    ARG="${EXTRA_ARGS[0]}"
    EXTRA_ARGS=("${EXTRA_ARGS[@]:1}")

    case "$ARG" in
      --output)
        if [[ "${#EXTRA_ARGS[@]}" -gt 0 ]]; then
          EXTRA_ARGS=("${EXTRA_ARGS[@]:1}")
        fi
        ;;
      --output=*)
        :
        ;;
      -o)
        if [[ "${#EXTRA_ARGS[@]}" -gt 0 ]]; then
          EXTRA_ARGS=("${EXTRA_ARGS[@]:1}")
        fi
        ;;
      *)
        FILTERED_ARGS+=("$ARG")
        ;;
    esac
  done
fi

"$BIN_PATH" "$TARGET" --output "$OUTPUT_DIR" --concurrency "$CONCURRENCY" "${FILTERED_ARGS[@]}"
