{ stdenv
, lib
, fetchzip
, freeglut
, libXmu
, libXi
, libX11
, libICE
, libGLU
, libGL
, libSM
, libXext
, glibc
, lua
, glfw
, luabind
, libgccjit
, dialog
, openssl
, makeWrapper
}:

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

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

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

  buildInputs = [ makeWrapper ];
  installPhase = ''
    cp -r ./ $out
    #rm $out/bin/*.so
    mkdir $out/oldbin
    cp $out/bin/liblua.so $out/oldbin/liblua.so
    cp $out/bin/libluabind.so $out/oldbin/libluabind.so
    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 = "IceSL is a GPU-accelerated procedural modeler and slicer for 3D printing.";
    homepage = http://shapeforge.loria.fr/icesl/index.html;
    license = licenses.inria-icesl;
    sourceProvenance = with sourceTypes; [ binaryNativeCode ];
    platforms = [ "i686-linux" "x86_64-linux" ];
    maintainers = with maintainers; [ mgttlinger ];
  };
}
