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

let
  steam_pcsx2 = pkgs.writeScriptBin "steam_pcsx2" ''
    export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:${pkgs.libglvnd}/lib"
    exec ${pkgs.pcsx2}/bin/pcsx2-qt "''${@}"
  '';
in
{
  imports = [ ];

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

  config = lib.mkIf config.me.pcsx2.enable (
    lib.mkMerge [
      (lib.mkIf config.me.graphical {
        home.packages = with pkgs; [
          pcsx2
          steam_pcsx2
        ];

        home.file.".config/PCSX2/inis/PCSX2.ini" = {
          source = ./files/PCSX2.ini;
        };

        me.persist.directories = [ ".config/PCSX2/memcards" ];
        me.state.directories = [
          ".config/PCSX2/cache"
          ".config/PCSX2/sstates"
          ".config/PCSX2/snaps"
          ".config/PCSX2/covers"
          ".config/PCSX2/videos"
        ];

        nixpkgs.overlays = [
          (
            final: prev:
            let
              optimizeWithFlags =
                pkg: flags:
                pkg.overrideAttrs (old: {
                  env.CXXFLAGS = (old.env.CXXFLAGS or "") + (lib.strings.concatStringsSep " " flags);
                });
              original_package =
                if config.me.optimizations.enable then
                  (optimizeWithFlags prev.pcsx2 [
                    "-march=znver2"
                    "-mtune=znver2"
                  ])
                else
                  prev.pcsx2;
            in
            {
              pcsx2 = pkgs.buildEnv {
                name = prev.pcsx2.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/PCSX2.desktop
                '';
              };
            }
          )
        ];
      })
    ]
  );
}
