{ pkgs ? import
    (builtins.fetchGit {
      name = "nixos-unstable";
      url = "https://github.com/nixos/nixpkgs";
      #ref = "refs/heads/nixos-22.11";
      #rev = "913a47cd064cc06440ea84e5e0452039a85781f0";
      #name = "nixos-22.11-2023_01_01";
      #url = "https://github.com/nixos/nixpkgs/";
      #ref = "refs/heads/nixos-22.11";
      #rev = "913a47cd064cc06440ea84e5e0452039a85781f0";
    })
    { }
}:

with pkgs;

let
  lpath = lib.makeLibraryPath [ libXmu libXi libX11 freeglut libICE libGLU libGL libSM libXext glibc glfw lua luabind libgccjit openssl ];
in

stdenv.mkDerivation rec {
  pname = "IceSL-${version}";
  version = "2.5.3-beta5";

  src =  if stdenv.hostPlatform.system == "x86_64-linux" then fetchurl {
    url = "https://icesl.loria.fr/assets/other/download.php?build=${version}&version=beta&os=amd64";
    extension = "zip";
    sha256 = "sha256-db4qj7hg0UnrlCnWAijvMWMgncUWPacnip3jdKU6Vl4=";
    #hash = "sha256-kR6pJodgIw1N6mfhoA58N3mlkCuKPkxQ2nvs2BGgIj0=";
  } else if stdenv.hostPlatform.system == "i686-linux" then fetchurl {
    url = "https://icesl.loria.fr/assets/other/download.php?build=${version}@version=stable&os=i386";
    extension = "zip";
    sha256 = "";
  } else throw "Unsupported architecture";

  nativeBuildInputs = [ makeWrapper ];
    #++ optionals cudaSupport [ addOpenGLRunpath ];
  buildInputs = [
    unzip
    autoPatchelfHook
    libXmu
    libXi
    libX11
    freeglut
    libICE
    libGLU
    libGL
    libSM
    libXext
    glibc
    glfw
    lua
    luabind
    libgccjit
    openssl
    #glew-egl
  ];

  phases = [
    "unpackPhase"
    "installPhase"
    "fixupPhase"
  ];

  unpackPhase = ''
    unzip $src
  '';

  installPhase = ''
    cp -r ./ $out
    rm $out/bin/*.so
    mkdir $out/oldbin
    mv $out/bin/IceSL-slicer $out/oldbin/IceSL-slicer
    runHook postInstall
  '';

  postInstall = ''
    patchelf --set-interpreter "$(cat $NIX_CC/nix-support/dynamic-linker)" \
      --set-rpath "${lpath}" \
      $out/oldbin/IceSL-slicer
    makeWrapper $out/oldbin/IceSL-slicer $out/bin/icesl --prefix PATH : ${dialog}/bin
  '';

  meta = with lib; {
    description = "GPU-accelerated procedural modeler and slicer for 3D printing";
    homepage = "https://icesl.loria.fr/";
    sourceProvenance = with sourceTypes; [ binaryNativeCode ];
    license = licenses.inria-icesl;
    platforms = [ "i686-linux" "x86_64-linux" ];
    maintainers = with maintainers; [ mgttlinger magoose ];
  };
}
