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

script_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
repo_root="$(cd "${script_dir}/.." && git rev-parse --path-format=absolute --show-toplevel)"
workspace_root="${repo_root}"
git_common_dir="$(cd "${repo_root}" && git rev-parse --path-format=absolute --git-common-dir)"
worktree_root="$(cd "${repo_root}" && git rev-parse --path-format=absolute --show-toplevel)"

hash_path() {
  if command -v shasum >/dev/null 2>&1; then
    printf '%s' "$1" | shasum | cut -c1-10
  elif command -v sha1sum >/dev/null 2>&1; then
    printf '%s' "$1" | sha1sum | cut -c1-10
  else
    printf '%s' "$1" | cksum | cut -d' ' -f1
  fi
}

sanitize_cache_key() {
  local raw="${1:-}"
  local key
  key="$(printf '%s' "${raw}" | LC_ALL=C tr -c 'A-Za-z0-9._@+-' '-')"
  printf '%s' "${key:-default}"
}

repo_slug="$(basename "${repo_root}")"
repo_key="${repo_slug}-$(hash_path "${git_common_dir}")"
target_cache_schema="v4"
toolchain_spec=""
toolchain_key="${MEERKAT_RUST_TOOLCHAIN_ID:-}"
toolchain_bin=""
toolchain_cargo=""
toolchain_rustc=""
toolchain_rustdoc=""
toolchain_rustfmt=""
resolved_toolchain_bin=""
toolchain_wrappers_supported=true

if [[ -n "${RUSTUP_TOOLCHAIN:-}" ]]; then
  toolchain_spec="${RUSTUP_TOOLCHAIN}"
  toolchain_key="${toolchain_key:-${toolchain_spec}}"
elif [[ -f "${repo_root}/rust-toolchain.toml" ]]; then
  toolchain_spec="$(awk -F '"' '/^[[:space:]]*channel[[:space:]]*=/ { print $2; exit }' "${repo_root}/rust-toolchain.toml")"
  toolchain_key="${toolchain_key:-${toolchain_spec}}"
elif [[ -f "${repo_root}/rust-toolchain" ]]; then
  toolchain_spec="$(sed -n 's/#.*//; /^[[:space:]]*$/d; s/^[[:space:]]*//; s/[[:space:]]*$//; p; q' "${repo_root}/rust-toolchain")"
  toolchain_key="${toolchain_key:-${toolchain_spec}}"
fi

if [[ -n "${toolchain_spec}" ]] && command -v rustup >/dev/null 2>&1; then
  rustc_verbose="$(rustup run "${toolchain_spec}" rustc -Vv 2>/dev/null || true)"
  if [[ -n "${rustc_verbose}" ]]; then
    rustc_release="$(awk -F ': ' '$1 == "release" { print $2; exit }' <<<"${rustc_verbose}")"
    rustc_host="$(awk -F ': ' '$1 == "host" { print $2; exit }' <<<"${rustc_verbose}")"
    rustc_commit="$(awk -F ': ' '$1 == "commit-hash" { print substr($2, 1, 10); exit }' <<<"${rustc_verbose}")"
    toolchain_key="${rustc_release:-${toolchain_key}}-${rustc_host:-unknown}-${rustc_commit:-unknown}"
  fi
  toolchain_cargo="$(rustup which --toolchain "${toolchain_spec}" cargo 2>/dev/null || true)"
  toolchain_rustc="$(rustup which --toolchain "${toolchain_spec}" rustc 2>/dev/null || true)"
  toolchain_rustdoc="$(rustup which --toolchain "${toolchain_spec}" rustdoc 2>/dev/null || true)"
  toolchain_rustfmt="$(rustup which --toolchain "${toolchain_spec}" rustfmt 2>/dev/null || true)"
  if [[ -n "${toolchain_cargo}" ]]; then
    resolved_toolchain_bin="$(dirname "${toolchain_cargo}")"
  fi
fi

toolchain_key="$(sanitize_cache_key "${toolchain_key:-default}")"

if [[ -n "${RUST_LANE_ID:-}" ]]; then
  lane_key="${RUST_LANE_ID}"
elif [[ -n "${MEERKAT_AGENT_LANE:-}" ]]; then
  lane_key="${MEERKAT_AGENT_LANE}"
elif [[ -n "${CODEX_AGENT_ID:-}" ]]; then
  lane_key="${CODEX_AGENT_ID}"
elif [[ -n "${GITHUB_JOB:-}" ]]; then
  if [[ -n "${GITHUB_RUN_ID:-}" ]]; then
    lane_key="gha-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT:-1}-${GITHUB_JOB}"
  else
    lane_key="gha-${GITHUB_JOB}"
  fi
else
  worktree_name="$(basename "${worktree_root}")"
  lane_key="${worktree_name}-$(hash_path "${worktree_root}")"
fi
lane_key="$(sanitize_cache_key "${lane_key}")"

if [[ "$(uname -s)" == "Darwin" ]]; then
  cache_root="${HOME}/Library/Caches/rust-workspaces"
else
  cache_root="${XDG_CACHE_HOME:-${HOME}/.cache}/rust-workspaces"
fi

case "$(uname -s)" in
  MINGW*|MSYS*|CYGWIN*)
    # Cargo executes RUSTC directly on Windows; a bash wrapper is not a valid
    # Win32 executable and fails before rustup can dispatch the pinned toolchain.
    toolchain_wrappers_supported=false
    ;;
esac

target_dir_was_set=false
if [[ -n "${CARGO_TARGET_DIR:-}" ]]; then
  target_dir_was_set=true
fi
cargo_home="${CARGO_HOME:-${cache_root}/${repo_key}/cargo-home}"
if [[ "${GITHUB_ACTIONS:-}" == "true" && "${cargo_home}" == "/tmp/meerkat-cargo-home" ]]; then
  cargo_home="${cargo_home}/${lane_key}"
fi
export CARGO_HOME="${cargo_home}"
export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-${cache_root}/${repo_key}/targets/${target_cache_schema}/${toolchain_key}/${lane_key}}"

mkdir -p "${CARGO_HOME}" "${CARGO_TARGET_DIR}"

if [[ "${GITHUB_ACTIONS:-}" == "true" && "${target_dir_was_set}" == "false" ]]; then
  if [[ "${CARGO_TARGET_DIR}" == "${repo_root}"* ]]; then
    echo "error: refusing to clean a Cargo target directory inside the repo tree" >&2
    exit 1
  fi
  target_marker="${CARGO_TARGET_DIR}/.repo-cargo-toolchain"
  target_marker_value="schema=${target_cache_schema}"$'\n'"toolchain=${toolchain_key}"$'\n'
  if [[ ! -f "${target_marker}" ]] || [[ "$(cat "${target_marker}")"$'\n' != "${target_marker_value}" ]]; then
    rm -rf "${CARGO_TARGET_DIR}"
    mkdir -p "${CARGO_TARGET_DIR}"
    printf '%s' "${target_marker_value}" >"${target_marker}"
  fi
fi

if [[ "${toolchain_wrappers_supported}" == "true" ]] && [[ -n "${toolchain_spec}" ]] && command -v rustup >/dev/null 2>&1; then
  toolchain_bin="${CARGO_HOME}/.repo-cargo-toolchain-bin/${toolchain_key}"
  mkdir -p "${toolchain_bin}"
  for tool in cargo rustc rustdoc rustfmt; do
    tool_path="${toolchain_bin}/${tool}"
    {
      printf '#!/usr/bin/env bash\n'
      printf 'exec rustup run %q %q "$@"\n' "${toolchain_spec}" "${tool}"
    } >"${tool_path}"
    chmod +x "${tool_path}"
  done
  toolchain_cargo="${toolchain_bin}/cargo"
  toolchain_rustc="${toolchain_bin}/rustc"
  toolchain_rustdoc="${toolchain_bin}/rustdoc"
  toolchain_rustfmt="${toolchain_bin}/rustfmt"
fi

if [[ "${1-}" == "--print-env" ]]; then
  printf '%s\n' \
    "repo_root=${repo_root}" \
    "workspace_root=${workspace_root}" \
    "repo_key=${repo_key}" \
    "target_cache_schema=${target_cache_schema}" \
    "toolchain_spec=${toolchain_spec}" \
    "toolchain_key=${toolchain_key}" \
    "RUSTUP_TOOLCHAIN=${toolchain_spec}" \
    "MEERKAT_RUST_TOOLCHAIN_BIN=${toolchain_bin}" \
    "RUSTC=${toolchain_rustc}" \
    "RUSTDOC=${toolchain_rustdoc}" \
    "RUSTFMT=${toolchain_rustfmt}" \
    "MEERKAT_RUST_RESOLVED_TOOLCHAIN_BIN=${resolved_toolchain_bin}" \
    "lane_key=${lane_key}" \
    "CARGO_HOME=${CARGO_HOME}" \
    "CARGO_TARGET_DIR=${CARGO_TARGET_DIR}"
  exit 0
fi

if [[ "${1-}" == "--doctor" ]]; then
  if [[ "${CARGO_HOME}" == "${repo_root}"* || "${CARGO_TARGET_DIR}" == "${repo_root}"* ]]; then
    echo "error: cache path resolved inside repo tree" >&2
    exit 1
  fi
  [[ -w "${CARGO_HOME}" ]] || { echo "error: CARGO_HOME not writable" >&2; exit 1; }
  [[ -w "${CARGO_TARGET_DIR}" ]] || { echo "error: CARGO_TARGET_DIR not writable" >&2; exit 1; }
  printf '%s\n' \
    "doctor=ok" \
    "repo_root=${repo_root}" \
    "workspace_root=${workspace_root}" \
    "repo_key=${repo_key}" \
    "target_cache_schema=${target_cache_schema}" \
    "toolchain_spec=${toolchain_spec}" \
    "toolchain_key=${toolchain_key}" \
    "RUSTUP_TOOLCHAIN=${toolchain_spec}" \
    "MEERKAT_RUST_TOOLCHAIN_BIN=${toolchain_bin}" \
    "RUSTC=${toolchain_rustc}" \
    "RUSTDOC=${toolchain_rustdoc}" \
    "RUSTFMT=${toolchain_rustfmt}" \
    "MEERKAT_RUST_RESOLVED_TOOLCHAIN_BIN=${resolved_toolchain_bin}" \
    "lane_key=${lane_key}" \
    "CARGO_HOME=${CARGO_HOME}" \
    "CARGO_TARGET_DIR=${CARGO_TARGET_DIR}"
  exit 0
fi

cd "${workspace_root}"

if [[ -n "${toolchain_spec}" ]]; then
  export RUSTUP_TOOLCHAIN="${toolchain_spec}"
  if [[ -n "${toolchain_bin}" ]]; then
    export PATH="${toolchain_bin}:${PATH}"
    export MEERKAT_RUST_TOOLCHAIN_BIN="${toolchain_bin}"
  fi
  if [[ -n "${toolchain_rustc}" ]]; then
    export RUSTC="${toolchain_rustc}"
  fi
  if [[ -n "${toolchain_rustdoc}" ]]; then
    export RUSTDOC="${toolchain_rustdoc}"
  fi
  if [[ -n "${toolchain_rustfmt}" ]]; then
    export RUSTFMT="${toolchain_rustfmt}"
  fi
fi

if [[ -n "${CARGO_BIN:-}" ]]; then
  cargo_cmd=("${CARGO_BIN}")
elif [[ -n "${toolchain_cargo}" ]]; then
  cargo_cmd=("${toolchain_cargo}")
elif [[ -n "${toolchain_spec}" ]] && command -v rustup >/dev/null 2>&1; then
  cargo_cmd=(rustup run "${toolchain_spec}" cargo)
elif command -v cargo >/dev/null 2>&1; then
  cargo_cmd=("$(command -v cargo)")
elif [[ -x "${HOME}/.cargo/bin/cargo" ]]; then
  cargo_cmd=("${HOME}/.cargo/bin/cargo")
  export PATH="${HOME}/.cargo/bin:${PATH}"
else
  cat >&2 <<'EOF'
error: cargo was not found on PATH.

Run `make install-build-deps` to install the Rust toolchain pinned by
rust-toolchain.toml, or set CARGO_BIN to an explicit cargo binary.
EOF
  exit 127
fi

exec "${cargo_cmd[@]}" "$@"
