# SPDX-FileCopyrightText: 2020 Luke Granger-Brown <depot@lukegb.com>
#
# SPDX-License-Identifier: Apache-2.0

{ buildBazelPackage, buildFHSUserEnv, openjdk11_headless, bazel, git, mercurial, makeWrapper, fetchFromGitHub }:
let
  hackedBazelTop = buildFHSUserEnv {
    name = "bazel";
    targetPkgs = pkgs: [
      (bazel.override { enableNixHacks = true; })
      openjdk11_headless
      git
      mercurial
    ];
    runScript = "/bin/bazel";
  };
  hackedBazel = hackedBazelTop // { override = x: hackedBazelTop; };
in
buildBazelPackage rec {
  name = "copybara";
  version = "master";
  bazel = hackedBazel;

  src = ../../third_party/copybara;

  nativeBuildInputs = [ git mercurial openjdk11_headless makeWrapper ];

  bazelTargets = [ "//java/com/google/copybara:copybara_deploy.jar" ];
  removeRulesCC = false;
  fetchConfigured = true;
  dontAddBazelOpts = true;
  bazelFlags = [
    "--javabase=@local_jdk//:jdk"
    "--host_javabase=@local_jdk//:jdk"
    "--java_toolchain=@bazel_tools//tools/jdk:toolchain_hostjdk8"
    "--host_java_toolchain=@bazel_tools//tools/jdk:toolchain_hostjdk8"
    "--define=EXECUTOR=remote"
  ];

  fetchAttrs = {
    sha256 = "sha256:0r3y4lxwf2kwdfvl5qqqr6kmc0gajsqr24fr7s3ygqjr22vn99qa";
    preHook = ''
      export COURSIER_CACHE="$(echo ''${NIX_BUILD_TOP}/tmp/coursier | sed -e 's,//,/,g')"
    '';
  };

  buildAttrs = {
    installPhase = ''
      mkdir -p $out/bin $out/share/java
      install -Dm755 bazel-bin/java/com/google/copybara/copybara_deploy.jar $out/share/java/copybara.jar
      makeWrapper ${openjdk11_headless}/bin/java $out/bin/copybara \
        --add-flags "-cp $out/share/java/copybara.jar com.google.copybara.Main"
    '';
  };
}