{ lib
, fetchFromGitHub
, stdenv
, coreutils
, iproute2
, openssl
, tcllauncher
, tcl
, tcllib
, tcltls
, tclx
, faup1090
, mlat-client
, which
, makeWrapper
}:

stdenv.mkDerivation rec {
  pname = "piaware";
  version = "8.2";

  src = fetchFromGitHub {
    owner = "flightaware";
    repo = "piaware";
    rev = "v${version}";
    sha256 = "sha256:163ywwgcv1ick7qj1cx2879nm9apv2fadx1sgpx6lw9llvxhkb9d";
  };

  postPatch = ''
    substituteInPlace package/fa_sysinfo.tcl \
      --replace "/bin/df" "${coreutils}/bin/df" \
      --replace "/sbin/ip" "${iproute2}/bin/ip" \
      --replace "|ip" "|${iproute2}/bin/ip"

    substituteInPlace programs/piaware/login.tcl \
      --replace "/bin/uname" "${coreutils}/bin/uname"

    substituteInPlace programs/piaware/helpers.tcl \
      --replace "/bin/uname" "${coreutils}/bin/uname"

    substituteInPlace programs/piaware/faup1090.tcl \
      --replace "/usr/lib/piaware/helpers/faup1090" "${faup1090}/bin/faup1090"

    substituteInPlace programs/piaware/mlat.tcl \
      --replace "/usr/lib/piaware/helpers/fa-mlat-client" "${mlat-client}/bin/fa-mlat-client"
  '';

  buildInputs = [
    tcllauncher
  ];
  nativeBuildInputs = [
    openssl
    which
    tcl
    makeWrapper
  ];

  makeFlags = "PREFIX= DESTDIR=${placeholder "out"}";
  enableParallelBuilding = true;

  postInstall = ''
    wrapProgram $out/bin/piaware \
      --suffix TCLLIBPATH ' ' "${tcltls}/lib ${tcllib}/lib ${tcllauncher}/lib ${tclx}/lib ${placeholder "out"}/lib"
    wrapProgram $out/bin/piaware-config \
      --suffix TCLLIBPATH ' ' "${tcltls}/lib ${tcllib}/lib ${tcllauncher}/lib ${tclx}/lib ${placeholder "out"}/lib"
    wrapProgram $out/bin/piaware-status \
      --suffix TCLLIBPATH ' ' "${tcltls}/lib ${tcllib}/lib ${tcllauncher}/lib ${tclx}/lib ${placeholder "out"}/lib"
    wrapProgram $out/bin/pirehose \
      --suffix TCLLIBPATH ' ' "${tcltls}/lib ${tcllib}/lib ${tcllauncher}/lib ${tclx}/lib ${placeholder "out"}/lib"
  '';
}