#
# Binary ninja.
#
# vim: et:ts=2:sw=2:
#
{
  lib,
  stdenv,
  autoPatchelfHook,
  makeWrapper,
  writeText,
  unzip,
  libGL,
  xorg,
  glib,
  fontconfig,
  dbus,
  xkeyboard_config,
  libxkbcommon,
  wayland,
  python3,
  svd2py,
  qt6,
  libxml2
}:
let
  desktopFile = writeText "binary-ninja.desktop" ''
		[Desktop Entry]
    Type=Application
    Name=Binary Ninja
    Exec=/run/current-system/sw/bin/binaryninja
    Icon=/run/current-system/sw/share/icons/binary-ninja.png
    Categories=Development;
  '';

  # Additional packages to put in Binja's python envrioment.
  additional-python-packages = pypkgs: with pypkgs; [
    click
    colorama
    pyyaml
    svd2py
  ];

  # Python specialized for our environment.
  binja-python = python3.withPackages additional-python-packages;

  binary-ninja = stdenv.mkDerivation {
    pname = "binary-ninja";
    version = "4.0.5902";

    nativeBuildInputs = [
      autoPatchelfHook
      qt6.wrapQtAppsHook
      makeWrapper
      unzip
    ];

    buildInputs = [
      libGL
      stdenv.cc.cc.lib
      glib
      libxkbcommon
      fontconfig
      xorg.libXi
      xorg.libXrender
      xorg.libxcb
      xorg.xcbutil
      xorg.xcbutilwm
      xorg.xcbutilimage
      xorg.xcbutilkeysyms
      xorg.xcbutilrenderutil
      qt6.qtdeclarative
      wayland
      binja-python
      libxml2
      dbus
    ];

    autoPatchelfIgnoreMissingDeps = [ "libxml2.so.2" ];

    propogatedBuildInputs = (additional-python-packages python3.pkgs);

    # Use our local zip directly.
    src = if stdenv.isAarch64 then
    	../proprietary/binja/binaryninja_personal_linux_aarch64.zip
    else
    	../proprietary/binja/binaryninja_personal_linux_x64.zip;


    installPhase = ''
      mkdir -p $out/opt
      cp -r * $out/opt
      chmod +x $out/opt/binaryninja

      # Icons.
      mkdir -p $out/share/icons
      cp -r docs/img/logo.png $out/share/icons/binary-ninja.png

			# Application file.
      mkdir -p $out/share/applications
  		cp ${desktopFile} $out/share/applications/binary-ninja.desktop

      mkdir -p $out/bin
      makeWrapper $out/opt/binaryninja \
            $out/bin/binaryninja \
            --set "PYTHONHOME" "${binja-python}" \
            --prefix "QT_XKB_CONFIG_ROOT" ":" "${xkeyboard_config}/share/X11/xkb" \
            --prefix "LD_LIBRARY_PATH" ":" "${lib.makeLibraryPath binary-ninja.buildInputs}"
      ln -s $out/bin/binaryninja $out/bin/binary-ninja
    '';
  };
in
binary-ninja
