{ stdenv
, lib
, withCFlags
, intelPackages
, fetchFromGitHub
, automake
, autoconf
, libtool
, gnumake
, autoreconfHook
, boost
, opensycl ? null
, adaptivecpp ? null
, useIntel ? true
  # TODO: move back to main branch and release
, useGit ? true
, gitUrl ? "git@gitlab-internal.bsc.es:task-awareness/tasycl/tasycl.git"
, gitBranch ? "fix/various"
, gitCommit ? "8be4729ded0ef64f028e98eb2b2baf2ccba7ff42"
}:

assert (useIntel || opensycl != null || adaptivecpp != null);

let
  # opensycl has migrated to adaptivecpp
  acpp-flags =
    if adaptivecpp == null then
      [ "-L${opensycl}/lib" "-lhipSYCL-rt" "-I${opensycl}/include" ]
    else
      [ "-L${adaptivecpp}/lib" "-lacpp-rt" "-I${adaptivecpp}/include" ]
  ;

  variant = if useIntel then "intel" else "acpp";

  syclStdenv =
    if useIntel then
      # If we don't set optimization level, separateDebugInfo sets ggdb and
      # intel disables all optimizations
      withCFlags ["-O3"] intelPackages.stdenv
    else
      withCFlags acpp-flags stdenv
  ;

  release = rec {
    version = "2.0.0";
    src = fetchFromGitHub {
      owner = "bsc-pm";
      repo = "tasycl";
      rev = version;
      hash = "sha256-Z4d45baVBhE9NW8Ww948M78TJx7BpxTr9pGJvJO9hdI=";
    };
  };

  git = rec {
    version = src.shortRev;
    src = builtins.fetchGit {
      url = gitUrl;
      ref = gitBranch;
      rev = gitCommit;
    };
  };

  source = if (useGit) then git else release;

  isOldRelease = (!useGit && (builtins.compareVersions source.version "2.0.0" <= 0));

in

assert !isOldRelease || useIntel; # old releases only work with intel

syclStdenv.mkDerivation {
  pname = "tasycl";
  inherit (source) src version;

  enableParallelBuilding = true;
  separateDebugInfo = true;

  nativeBuildInputs = [
    autoreconfHook
    automake
    autoconf
    libtool
    gnumake
  ];

  buildInputs = [
    boost
  ];

  # only needed for release versions prior or equal to 2.0.0
  configureFlags = lib.optionals isOldRelease [ "--with-sycl-include=${intelPackages.icx.cc}/include/sycl" ];

  # add symlinks so we can explicitly link with tasycl-intel / tasycl-acpp
  postInstall = ''
    pushd $out/lib
    for i in libtasycl* ; do
      ln -s "$i" "''\${i/tasycl/tasycl-${variant}}"
    done
    popd
  '';

  hardeningDisable = [ "all" ];
}
