{ lib
, libicns
, p7zip
, fetchzip
, stdenvNoCC
, makeDesktopItem
, buildFHSUserEnv
, workdir ? "/tmp/blhelisuite32" }: let
  name = "BLHeliSuite32";
  pname = "blhelisuite32";
  version = "32.10";
  suffix = "1044";

  dist = fetchzip {
    name = "${pname}-dist";
    url = "https://github.com/bitdump/BLHeli/releases/download/Rev${version}/${name}xLinux64_${suffix}.zip";
    hash = "sha256-y4S824s9Ipxb1M1IeD6Lo6k7hmm8CEmPflvhaqZz+84=";
  };

  desktopItem = makeDesktopItem {
    name = pname;
    exec = pname;
    icon = pname;
    comment = "This Application may flash and configure BLHeli_32 based ESCs";
    desktopName = name;
    genericName = "BLHeli for brushless ESC firmware";
  };

  icons = stdenvNoCC.mkDerivation {
    pname = "${pname}-icons";
    inherit version;
    src = fetchzip {
      name = "${pname}-macos";
      url = "https://github.com/bitdump/BLHeli/releases/download/Rev${version}/${name}xm_MacOS64_${suffix}.zip";
      hash = "sha256-StRnrVI8p51vNsTMO1LtaZvENbG7XZ1V/mKHe4pO7kU=";
    };

    nativeBuildInputs = [ libicns p7zip ];

    configurePhase = ''
      7z x *.dmg
    '';

    buildPhase = ''
      icns2png -x ${name}xm_MacOS64_${suffix}/${name}xm.app/Contents/Resources/${name}xm.icns
    '';

    installPhase = ''
      mkdir -p "$out"
      cp -r ${name}*.png "$out"
    '';
  };

  linked = stdenvNoCC.mkDerivation {
    inherit pname version;
    phases = [ "unpackPhase" "patchPhase" "installPhase" ];
    src = dist;

    installPhase = ''
      cp -r . "$out"

      # BLHeliSuite32 tries to write next to its binary
      ln -s ${workdir}/settings $out/Settings
      ln -s ${workdir}/music $out/Music
    '';
  };
in buildFHSUserEnv {
  inherit pname;
  targetPkgs = pkgs: (with pkgs; [
    glib libGL curl
    libgcc gtk3
    zlib systemdLibs
  ]);
  extraInstallCommands = let
    mkIconScale = scale:
    "install -m 444 -D ${icons}/${name}xm_${scale}x${scale}x32.png $out/share/icons/hicolor/${scale}x${scale}/apps/${pname}.png";
  in ''
    ${mkIconScale "16"}
    ${mkIconScale "32"}
    ${mkIconScale "64"}
    ${mkIconScale "128"}
    ${mkIconScale "256"}
    ${mkIconScale "512"}
    ${mkIconScale "1024"}
    cp -r ${desktopItem}/share/applications $out/share/
  '';

  runScript = "sh -c '" +
  "mkdir -p ${workdir}/settings && " +
  "mkdir -p ${workdir}/music && " +
  "exec ${linked}/${name}xl'";
}
