{ lib
, stdenv
, fetchFromGitHub
, asciidoc
, docbook_xml_dtd_45
, docbook_xsl
, installShellFiles
, libxslt
, python3
, re2c
, buildPackages
, buildDocs ? true
, nix-update-script
}:

stdenv.mkDerivation (finalAttrs: {
  pname = "ninja";
  version = "1.12.1";

  src = fetchFromGitHub {
    owner = "ninja-build";
    repo = "ninja";
    rev = "v${finalAttrs.version}";
    hash = "sha256-RT5u+TDvWxG5EVQEYj931EZyrHUSAqK73OKDAascAwA=";
  };

  depsBuildBuild = [ buildPackages.stdenv.cc ];

  nativeBuildInputs = [
    python3
    re2c
    installShellFiles
  ]
  ++ lib.optionals buildDocs [
    asciidoc
    docbook_xml_dtd_45
    docbook_xsl
    libxslt.bin
  ];

  postPatch = ''
    # write rebuild args to file after bootstrap
    substituteInPlace configure.py --replace "subprocess.check_call(rebuild_args)" "open('rebuild_args','w').write(rebuild_args[0])"
  '';

  buildPhase = ''
    runHook preBuild

    # for list of env vars
    # see https://github.com/ninja-build/ninja/blob/v1.11.1/configure.py#L264
    CXX="$CXX_FOR_BUILD" \
    AR="$AR_FOR_BUILD" \
    CFLAGS="$CFLAGS_FOR_BUILD" \
    CXXFLAGS="$CXXFLAGS_FOR_BUILD" \
    LDFLAGS="$LDFLAGS_FOR_BUILD" \
    python configure.py --bootstrap
    python configure.py

    source rebuild_args
  '' + lib.optionalString buildDocs ''
    # "./ninja -vn manual" output copied here to support cross compilation.
    asciidoc -b docbook -d book -o build/manual.xml doc/manual.asciidoc
    xsltproc --nonet doc/docbook.xsl build/manual.xml > doc/manual.html
  '' + ''

    runHook postBuild
  '';

  installPhase = ''
    runHook preInstall

    install -Dm555 -t $out/bin ninja
    installShellCompletion --name ninja \
      --bash misc/bash-completion \
      --zsh misc/zsh-completion
  '' + lib.optionalString buildDocs ''
    install -Dm444 -t $out/share/doc/ninja doc/manual.asciidoc doc/manual.html
  '' + ''

    runHook postInstall
  '';

  setupHook = ./setup-hook.sh;

  passthru.updateScript = nix-update-script {};

  meta = {
    description = "Small build system with a focus on speed";
    mainProgram = "ninja";
    longDescription = ''
      Ninja is a small build system with a focus on speed. It differs from
      other build systems in two major respects: it is designed to have its
      input files generated by a higher-level build system, and it is designed
      to run builds as fast as possible.
    '';
    homepage = "https://ninja-build.org/";
    license = lib.licenses.asl20;
    platforms = lib.platforms.unix;
    maintainers = with lib.maintainers; [ thoughtpolice bjornfor orivej ];
  };
})
