#!/usr/bin/env bash
# Opt-in local build speedup for contributors (Linux x86_64):
#   - lld as the linker (via clang), instead of the default GNU ld/gold
#   - sccache as the rustc wrapper, to reuse compiled objects across
#     `cargo clean` and branch switches
#
# Measured on this crate (~700 dependencies): clean build 3m18s -> ~2m15s,
# incremental single-crate rebuild 46s -> 21s.
#
# This only writes rust/.cargo/config.toml, which is gitignored on purpose
# (it assumes clang/lld/sccache are installed — a bare `cargo build` must
# keep working for anyone without them). Run this script once per machine.
set -euo pipefail

cd "$(dirname "${BASH_SOURCE[0]}")/.."

CONFIG_DIR=".cargo"
CONFIG_FILE="$CONFIG_DIR/config.toml"

if [[ -f "$CONFIG_FILE" ]]; then
  echo "note: $CONFIG_FILE already exists — leaving it untouched."
  echo "      delete it first if you want this script to regenerate it."
  exit 0
fi

missing=()

if ! command -v clang >/dev/null 2>&1; then
  missing+=("clang")
fi

# clang echoes the tool name back unchanged (not empty) when it can't
# resolve it internally, so "found" means the output differs from the input.
if command -v clang >/dev/null 2>&1; then
  lld_probe="$(clang -print-prog-name=ld.lld 2>/dev/null || true)"
  if [[ "$lld_probe" == "ld.lld" ]] && ! command -v ld.lld >/dev/null 2>&1; then
    missing+=("lld")
  fi
fi

if (( ${#missing[@]} > 0 )); then
  echo "Missing: ${missing[*]}"
  echo "Install on Debian/Ubuntu/Kali:"
  echo "  sudo apt-get install -y ${missing[*]}"
  echo "Then re-run this script."
  exit 1
fi

if ! command -v sccache >/dev/null 2>&1; then
  echo "sccache not found — installing via cargo (no sudo needed)..."
  cargo install sccache --locked
fi

if ! command -v sccache >/dev/null 2>&1; then
  cargo_bin="$HOME/.cargo/bin"
  echo "warning: sccache was installed but isn't on PATH."
  echo "  Add this to your shell rc: export PATH=\"$cargo_bin:\$PATH\""
fi

mkdir -p "$CONFIG_DIR"
cat > "$CONFIG_FILE" <<'EOF'
# Generated by scripts/setup-fast-build.sh — safe to delete and regenerate.
# lld links noticeably faster than GNU ld/gold on this crate's size (700+
# dependency graph); clang is used as the link driver since gcc's collect2
# can fail to locate GNU ld directly on some systems, but reliably finds lld.
[target.x86_64-unknown-linux-gnu]
linker = "clang"
rustflags = ["-C", "link-arg=-fuse-ld=lld"]

# Caches compiled objects across `cargo clean` / branch switches. No effect
# on plain incremental rebuilds (already covered by cargo's own incremental
# compilation + lld above). Relies on `sccache` being on PATH.
[build]
rustc-wrapper = "sccache"
EOF

echo "Wrote $CONFIG_FILE"
echo "Try it: cargo clean && cargo build"
