{
  config,
  lib,
  pkgs,
  ...
}:

let
  steam_spaghettikart = pkgs.writeScriptBin "steam_Spaghettify" ''
    export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:${pkgs.libglvnd}/lib"
    exec ${pkgs.spaghettikart}/bin/Spaghettify "''${@}"
  '';
in
{
  imports = [ ];

  options.me = {
    spaghettikart.enable = lib.mkOption {
      type = lib.types.bool;
      default = false;
      example = true;
      description = "Whether we want to install spaghettikart.";
    };
  };

  config = lib.mkIf config.me.spaghettikart.enable (
    lib.mkMerge [
      {
        allowedUnfree = [ "spaghettikart" ];
      }
      (lib.mkIf config.me.graphical {
        home.packages = with pkgs; [
          spaghettikart
          steam_spaghettikart
        ];

        home.file.".local/share/spaghettikart/spaghettify.cfg.json" = {
          source = ./files/spaghettify.cfg.json;
        };

        home.persistence."/home/deck/.persist" = {
          files = [
            ".local/share/spaghettikart/default.sav"
            ".local/share/spaghettikart/mk64.o2r"
          ];
        };

        nixpkgs.overlays = [
          (
            final: prev:
            let
              modified_package = (pkgs.callPackage ./package/package.nix { });
              optimizeWithFlags =
                pkg: flags:
                pkg.overrideAttrs (old: {
                  NIX_CFLAGS_COMPILE = [ (old.NIX_CFLAGS_COMPILE or "") ] ++ flags;
                });
              original_package =
                if config.me.optimizations.enable then
                  (optimizeWithFlags modified_package [
                    "-march=znver2"
                    "-mtune=znver2"
                  ])
                else
                  modified_package;
            in
            {
              spaghettikart = pkgs.buildEnv {
                name = prev.spaghettikart.name;
                paths = [
                  (config.lib.nixGL.wrap original_package)
                ];
                extraOutputsToInstall = [
                  "man"
                  "doc"
                  "info"
                ];
                # We have to use 555 instead of the normal 444 here because the .desktop file ends up inside $HOME on steam deck and desktop files must be either not in $HOME or must be executable, otherwise KDE Plasma refuses to execute them.
                postBuild = ''
                  chmod 0555 $out/share/applications/spaghettikart.desktop
                '';
              };
            }
          )
        ];
      })
    ]
  );
}
