#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
CRATE_DIR="$(cd -- "${SCRIPT_DIR}/../.." && pwd)"
BIN_PATH="${CRATE_DIR}/target/debug/sgclaw"
MANIFEST_PATH="${CRATE_DIR}/Cargo.toml"
RULES_SRC_PATH="${CRATE_DIR}/resources/rules.json"
RULES_DEST_PATH="${CRATE_DIR}/target/debug/resources/rules.json"

needs_build=0
if [[ ! -x "${BIN_PATH}" ]]; then
  needs_build=1
elif [[ "${MANIFEST_PATH}" -nt "${BIN_PATH}" ]]; then
  needs_build=1
elif [[ "${CRATE_DIR}/Cargo.lock" -nt "${BIN_PATH}" ]]; then
  needs_build=1
elif find \
  "${CRATE_DIR}/src" \
  "${CRATE_DIR}/third_party/zeroclaw/src" \
  "${CRATE_DIR}/../skill_lib" \
  -type f -newer "${BIN_PATH}" -print -quit | grep -q .; then
  needs_build=1
fi

if [[ "${needs_build}" -eq 1 ]]; then
  cargo build --manifest-path "${MANIFEST_PATH}" --bin sgclaw
fi

if [[ ! -f "${RULES_DEST_PATH}" || "${RULES_SRC_PATH}" -nt "${RULES_DEST_PATH}" ]]; then
  mkdir -p "$(dirname -- "${RULES_DEST_PATH}")"
  cp "${RULES_SRC_PATH}" "${RULES_DEST_PATH}"
fi

exec "${BIN_PATH}" "$@"
