{ lib
, pkgs
, stdenv
, fetchFromGitHub
, dedicated ? false # dedicated server
, gamedir ? "valve"
, enableBsp2 ? false # bsp2 support (for quake)
, enableGles1 ? false # gles1 renderer (nanogl)
, enableGles2 ? false # gles2 renderer (glwes)
, enableGl4es ? false # gles2 renderer (gl4es)
, enableGl ? true # opengl renderer
, enableSoft ? true # soft renderer
, enableUtils ? false # mdldec
}:

stdenv.mkDerivation {
  pname = "xash3d-fwgs";
  version = "2023-03-01";

  nativeBuildInputs = with pkgs; [python3 pkg-config makeWrapper];
  buildInputs = with pkgs; [SDL2 libopus freetype fontconfig];

  src = fetchFromGitHub {
    owner = "FWGS";
    repo = "xash3d-fwgs";
    rev = "7e9d46689ca76d6bf1669ada6344fc724dd683cf";
    sha256 = "sha256-rvONYm1Gz9PpK8KY6RIIJ82FtxGcWe/4YoT2eV4sCOc=";
    fetchSubmodules = true;
  };
  patches = [ ./change-zip-date.patch ];

  configurePhase = let
    optionals = lib.optionals;
    optional = (cond: val: optionals cond [val]);
    flags = ["-8" "-P" "--prefix=/"]
      ++ (optional dedicated "-d")
      ++ (optionals (gamedir != "valve") ["--gamedir" gamedir])
      ++ (optional enableBsp2 "--enable-bsp2")
      ++ (optional enableGles1 "--enable-gles1")
      ++ (optional enableGles2 "--enable-gles2")
      ++ (optional enableGl4es "--enable-gl4es")
      ++ (optional (!enableGl) "--disable-gl")
      ++ (optional (!enableSoft) "--disable-soft")
      ++ (optional enableUtils "--enable-utils")
    ;
  in ''
    python3 ./waf configure -T release ${lib.strings.escapeShellArgs flags}
  '';

  buildPhase = ''
    python3 ./waf build
  '';

  installPhase = ''
    python3 ./waf install "--destdir=$out"
    mkdir $out/bin
    makeWrapper $out/lib/xash3d/xash3d $out/bin/xash3d --set XASH3D_EXTRAS_PAK1 $out/share/xash3d/valve/extras.pk3
  '';

  meta = with lib; {
    description = "Xash3D FWGS engine";
    homepage = "https://github.com/FWGS/xash3d-fwgs";
    # this is a mess because of vendoring...
    # maybe the correct thing to do use to simply use `[ unfree gpl3Plus ]` instead
    license = with licenses; [ unfree gpl2Plus gpl3Plus lgpl3Plus mit bsd3 ];
    # maintainers = with maintainers; [ chayleaf ];
  };
}