{ lib
, pkgs
, buildGoModule
, fetchFromGitHub
, buildNpmPackage
, nixosTests
, caddy
, testers
, installShellFiles
, stdenv
}:

let
  version = "1.41.0";
  src = fetchFromGitHub {
    owner = "sbondCo";
    repo = "Watcharr";
    rev = "v${version}";
    hash = "sha256-ZvCxgfZZ9pbp+NvH+IhWphJWnAwgAH0x/REPd/XxJ70=";
  };

  frontend = buildNpmPackage {
    pname = "watcharr-ui";
    inherit version src;
    npmDepsHash = "sha256-73paI0y4QyzkEnU99f1HeLD/hW8GP3F9N8tGGQnloH8=";

    installPhase = ''
      cp -r build $out
      cp package.json package-lock.json $out
      cd $out && npm ci --omit=dev
    '';
  };
in
buildGoModule {
  pname = "watcharr";
  inherit version;

  src = src + "/server";

  vendorHash = "sha256-86pFpS8ZSj+c7vwn0QCwzXlvVYJIf3SBj4X81zlwBWQ=";

  # Inject frontend assets into go embed
  prePatch = ''
    # rm -rf ui
    # ln -s ${frontend} ui
    substituteInPlace watcharr.go \
        --replace-fail ui/index.js ${frontend}/index.js \
        --replace-fail \"127.0.0.1:3000\" "\"127.0.0.1:\"+os.Getenv(\"PORT\")"
  '';

  buildInputs = [ pkgs.makeWrapper ];

  postFixup = ''
    wrapProgram "$out/bin/Watcharr" --prefix PATH : "${lib.makeBinPath [ pkgs.nodejs ]}"
  '';

  meta = with lib; {
    homepage = "https://watcharr.app/";
    description = "Open source, self-hostable watched list for all your content with user authentication, modern and clean UI and a very simple setup";
    license = licenses.asl20;
    # mainProgram = "caddy";
    maintainers = with maintainers; [ nyanloutre ];
  };
}