#!/usr/bin/env bash
set -euo pipefail

INCLUDED_BUILDS_FILE="included-builds.txt"

main() {
  if [[ $# -eq 0 ]]; then
    echo "Usage: include-build.sh [-r [build-path...]] <relative-build-path>..."
    exit 1
  fi

  if [[ "$1" == "-r" ]]; then
    shift
    remove_builds "$@"
  else
    add_builds "$@"
  fi
}

add_builds() {
  ensure_init_script
  ensure_global_gitignore_entry "$INCLUDED_BUILDS_FILE"

  for build_path in "$@"; do
    ensure_include_builds_entry "$build_path"
  done

  echo "Done. All builds are now included via $INCLUDED_BUILDS_FILE."
}

remove_builds() {

  if [[ $# -eq 0 ]]; then
    rm -rf "$INCLUDED_BUILDS_FILE"
    echo "Removed all included builds."
  else
    for build_path in "$@"; do
      remove_include_builds_entry "$build_path"
    done
  fi
}

ensure_init_script() {
  local init_dir="$HOME/.gradle/init.d"
  local init_script="$init_dir/include-builds.init.gradle.kts"

  if [[ -f "$init_script" ]]; then
    return
  fi

  mkdir -p "$init_dir"
  cat > "$init_script" << GRADLE
settingsEvaluated {
  val includeFile = settingsDir.resolve("$INCLUDED_BUILDS_FILE")
  if (includeFile.isFile) {
    includeFile.readLines()
      .map { it.trim() }
      .filter { it.isNotEmpty() && !it.startsWith("#") }
      .forEach { includeBuild(it) }
  }
}
GRADLE
  echo "Created init script: $init_script"
}

ensure_global_gitignore_entry() {
  local entry="$1"
  local gitignore
  gitignore="$(git config --global core.excludesfile 2>/dev/null || true)"

  if [[ -z "$gitignore" ]]; then
    gitignore="$HOME/.gitignore_global"
    git config --global core.excludesfile "$gitignore"
    echo "Set global gitignore to: $gitignore"
  fi

  # Expand ~ if present
  gitignore="${gitignore/#\~/$HOME}"

  if [[ ! -f "$gitignore" ]]; then
    echo "$entry" > "$gitignore"
    echo "Added '$entry' to $gitignore"
    return
  elif ! grep -qxF "$entry" "$gitignore"; then
    echo "$entry" >> "$gitignore"
    echo "Added '$entry' to $gitignore"
  fi
}

ensure_include_builds_entry() {
  local build_path="$1"

  if [[ ! -f "$INCLUDED_BUILDS_FILE" ]]; then
    echo "$build_path" > "$INCLUDED_BUILDS_FILE"
    echo "Created $INCLUDED_BUILDS_FILE with '$build_path'"
    return
  fi

  if ! grep -qxF "$build_path" "$INCLUDED_BUILDS_FILE"; then
    echo "$build_path" >> "$INCLUDED_BUILDS_FILE"
    echo "Added '$build_path' to $INCLUDED_BUILDS_FILE"
  else
    echo "'$build_path' already in $INCLUDED_BUILDS_FILE"
  fi
}

remove_include_builds_entry() {
  local build_path="$1"

  if ! grep -qxF "$build_path" "$INCLUDED_BUILDS_FILE"; then
    echo "'$build_path' not found in $INCLUDED_BUILDS_FILE"
    return
  fi

  sed -i '' "/^${build_path//\//\\/}$/d" "$INCLUDED_BUILDS_FILE"
  echo "Removed '$build_path' from $INCLUDED_BUILDS_FILE"
}

main "$@"
