#
# Webserial for firefox.
#
{ lib
, stdenv
, fetchFromGitHub
, ws-server
, cjson
, libserialport
, linuxHeaders
, glibc
}:
stdenv.mkDerivation rec {
  pname = "firefox-webserial";
  version = "0.3.2";

  src = fetchFromGitHub {
    owner = "kuba2k2";
    repo = "firefox-webserial";
    rev = "v${version}";
    hash = "sha256-ML5AtkR2GGZ99wuE+GiZA5Vb9pZG62AjRwV5sL5dK/U=";
  };

	# Things that need to be copied into our build.
  extra_src= ./extra_src;

  buildInputs = [
    linuxHeaders
    libserialport
		ws-server
		cjson
		glibc
  ];

	# Build it ourselves, since its build system is _wonk_.
  buildPhase = ''
		cp -r $src/native/src/* .
		cp ${extra_src}/* .

		gcc -o ${meta.mainProgram} *.c -pthread \
			${ws-server}/lib/libws.a \
			${cjson}/lib/libcjson.so \
			-DSP_PRIV="" \
			-I${cjson}/include/cjson \
			-I${ws-server}/include/wsserver \
			-I. \
  '';

  installPhase = ''
  	mkdir -p $out/bin

  	# Copy our main program...
		cp ${meta.mainProgram} $out/bin/

		# ... and the config for it.
    mkdir -p "$out/lib/mozilla/native-messaging-hosts"
    sed -i -e "s|REPLACE_ME_WITH_SED|$out/bin/${meta.mainProgram}|" "webserial.json"
    cp webserial.json "$out/lib/mozilla/native-messaging-hosts/io.github.kuba2k2.webserial.json"
  '';

  meta = with lib; {
    description = "WebSerial API Polyfill for Mozilla Firefox browser";
    homepage = "https://github.com/kuba2k2/firefox-webserial/releases/download/v0.3.2/firefox-webserial-linux-x86-64";
    license = licenses.mit;
    maintainers = with maintainers; [ ];
    mainProgram = pname;
    platforms = platforms.all;
  };
}
