{ pkgs
, defaultSccacheDir
, defaultSccacheConfigPath
, defaultSccacheServerPath
, sccacheConfigText
}:

pkgs.writeShellApplication {
  name = "cg-cache";
  runtimeInputs = with pkgs; [
    coreutils
    findutils
    git
    gnugrep
    gnused
    jq
    sccache
  ];
  text = ''
    set -euo pipefail
    cache_secret_names=(
      AWS_ACCESS_KEY_ID
      AWS_SECRET_ACCESS_KEY
      AWS_SESSION_TOKEN
    )
    cache_required_secret_names=(
      AWS_ACCESS_KEY_ID
      AWS_SECRET_ACCESS_KEY
    )
    tmpdir="''${TMPDIR:-/tmp}"

    mkdir -p "$tmpdir"

    log() {
      printf '[cg-cache] %s\n' "$*" >&2
    }

    die() {
      log "error: $*"
      exit 1
    }

    run_maybe_dry() {
      if [[ -n "''${DRY_RUN_CMD:-}" ]]; then
        ''${DRY_RUN_CMD} "$@"
      else
        "$@"
      fi
    }

    repo_root="''${CG_ROOT:-}"
    if [[ -z "$repo_root" ]]; then
      repo_root="$(git rev-parse --show-toplevel 2>/dev/null || true)"
    fi
    if [[ -z "$repo_root" ]]; then
      die "missing CG_ROOT and failed to infer repo root"
    fi
    default_local_root="''${CG_SCCACHE_ROOT:-$repo_root/.devenv/sccache}"
    default_local_dir="''${CG_SCCACHE_DIR:-$default_local_root/cache}"
    default_local_config="''${CG_SCCACHE_CONFIG_PATH:-$default_local_root/config.toml}"
    default_local_server_uds="''${CG_SCCACHE_SERVER_PATH:-$default_local_root/builder.sock}"
    default_local_env_file="''${CG_SCCACHE_RUNTIME_ENV_PATH:-$repo_root/nix/sccache-runtime.env}"

    write_local_config() {
      local target="''${1:?target required}"
      local tmp

      tmp=$(mktemp "$tmpdir/cg-cache-config.XXXXXX")
      cat > "$tmp" <<'EOF'
${sccacheConfigText}
EOF
      run_maybe_dry install -D -m 0644 "$tmp" "$target"
      rm -f "$tmp"
    }

    write_local_runtime_env() {
      local target="''${1:?target required}"
      local tmp
      local name
      local value

      for name in "''${cache_required_secret_names[@]}"; do
        [[ -n "''${!name:-}" ]] || die "missing $name; export it directly or load it via dotenv"
      done

      tmp=$(mktemp "$tmpdir/cg-cache-runtime-env.XXXXXX")
      for name in "''${cache_secret_names[@]}"; do
        value="''${!name:-}"
        if [[ -n "$value" ]]; then
          printf '%s=%s\n' "$name" "$value" >> "$tmp"
        fi
      done
      run_maybe_dry install -D -m 0600 "$tmp" "$target"
      rm -f "$tmp"
    }

    load_runtime_env() {
      local env_file="''${1:?env file required}"
      if [[ -r "$env_file" ]]; then
        set -a
        # shellcheck disable=SC1090
        . "$env_file"
        set +a
      fi
    }

    install_local() {
      local cache_dir="''${1:-$default_local_dir}"
      local config_path="''${2:-$default_local_config}"
      local server_uds="''${3:-$default_local_server_uds}"
      local env_file="$default_local_env_file"

      mkdir -p "$cache_dir" "$(dirname "$config_path")" "$(dirname "$env_file")"
      write_local_config "$config_path"
      write_local_runtime_env "$env_file"
      printf 'Configured repo-local S3 sccache under %s\n' "$default_local_root"
      printf '  config: %s\n' "$config_path"
      printf '  env: %s\n' "$env_file"
      printf '  cache: %s\n' "$cache_dir"
      printf '  socket: %s\n' "$server_uds"
      printf '\n'
      printf '%s\n' 'Note: the runtime env file is part of the flake source so Chromium builds stay Nix-pure.'
      printf '%s\n' 'The committed nix/sccache-runtime.env file is the intended source of cache credentials for pure local and remote builds.'
    }

    start_local() {
      local cache_dir="''${1:-$default_local_dir}"
      local config_path="''${2:-$default_local_config}"
      local server_uds="''${3:-$default_local_server_uds}"
      local env_file="$default_local_env_file"

      [[ -r "$config_path" ]] || die "missing config: $config_path; run 'cg-cache install'"
      [[ -r "$env_file" ]] || die "missing runtime env: $env_file; run 'cg-cache install'"
      load_runtime_env "$env_file"
      : "''${AWS_ACCESS_KEY_ID:?missing AWS_ACCESS_KEY_ID in $env_file}"
      : "''${AWS_SECRET_ACCESS_KEY:?missing AWS_SECRET_ACCESS_KEY in $env_file}"
      export SCCACHE_CONF="$config_path"
      export SCCACHE_DIR="$cache_dir"
      export SCCACHE_SERVER_UDS="$server_uds"
      export SCCACHE_IDLE_TIMEOUT=0
      unset SCCACHE_NO_DAEMON
      unset SCCACHE_START_SERVER
      mkdir -p "$cache_dir" "$(dirname "$server_uds")"
      if ${pkgs.sccache}/bin/sccache --show-stats >/dev/null 2>&1; then
        printf 'sccache server already available on %s\n' "$server_uds"
      else
        rm -f "$server_uds"
        ${pkgs.sccache}/bin/sccache --start-server
        printf 'started repo-local sccache server on %s\n' "$server_uds"
      fi
    }

    status_local() {
      local cache_dir="''${1:-$default_local_dir}"
      local config_path="''${2:-$default_local_config}"
      local server_uds="''${3:-$default_local_server_uds}"
      local env_file="$default_local_env_file"

      printf 'config: %s\n' "$config_path"
      printf 'env: %s\n' "$env_file"
      printf 'cache: %s\n' "$cache_dir"
      printf 'socket: %s\n' "$server_uds"
      if [[ ! -r "$config_path" ]]; then
        die "missing config: $config_path"
      fi
      if [[ ! -r "$env_file" ]]; then
        die "missing runtime env: $env_file"
      fi
      grep -q '^\[cache\.s3\]' "$config_path" || die "config is not [cache.s3]: $config_path"
      load_runtime_env "$env_file"
      : "''${AWS_ACCESS_KEY_ID:?missing AWS_ACCESS_KEY_ID in $env_file}"
      : "''${AWS_SECRET_ACCESS_KEY:?missing AWS_SECRET_ACCESS_KEY in $env_file}"
      export SCCACHE_CONF="$config_path"
      export SCCACHE_DIR="$cache_dir"
      export SCCACHE_SERVER_UDS="$server_uds"
      ${pkgs.sccache}/bin/sccache --show-stats
    }

    usage() {
      cat <<EOF
Usage:
  cg-cache install [cache-dir] [config-path] [server-uds]
  cg-cache start [cache-dir] [config-path] [server-uds]
  cg-cache status [cache-dir] [config-path] [server-uds]
EOF
    }

    command="''${1:-}"
    shift || true

    case "$command" in
      install)
        install_local "$@"
        ;;
      start)
        start_local "$@"
        ;;
      status)
        status_local "$@"
        ;;
      *)
        usage >&2
        exit 1
        ;;
    esac
  '';
}
