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

let
  steam_rpcs3 = pkgs.writeScriptBin "steam_rpcs3" ''
    export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:${pkgs.libglvnd}/lib"
    exec ${pkgs.rpcs3}/bin/rpcs3 "''${@}"
  '';
  rpcs3_config_yaml = settingsFormat.generate "config.yml" config.me.rpcs3.config;
  settingsFormat = pkgs.formats.yaml { };

in
{
  imports = [ ];

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

    rpcs3.config = lib.mkOption rec {
      apply = lib.recursiveUpdate default;
      inherit (settingsFormat) type;
      default = {
        Core = {
          "Use LLVM CPU" = "znver2";
        };
        VFS = {
          "Enable /host_root/" = false;
        };
        Video = {
          "Write Color Buffers" = true;
          VSync = true;
          "Performance Overlay" = {
            Enabled = false;
          };
        };
        Miscellaneous = {
          "Pause emulation on RPCS3 focus loss" = true;
          "Start games in fullscreen mode" = true;
          "Pause Emulation During Home Menu" = false; # true makes the home menu slow
        };
      };
      example = null;
      description = "RPCS3's config.yml in nix form.";
    };
  };

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

        home.file.".config/rpcs3/config.yml" = lib.mkIf (config.me.rpcs3.config != null) {
          source = rpcs3_config_yaml;
        };
        home.file.".config/rpcs3/GuiConfigs/CurrentSettings.ini" = {
          source = ./files/CurrentSettings.ini;
        };

        me.persist.directories = [
          ".config/rpcs3/games" # Location of ROMs.
          ".config/rpcs3/dev_hdd0"
          ".config/rpcs3/dev_hdd1"
          ".config/rpcs3/savestates"
          ".config/rpcs3/dev_usb000"
          ".config/rpcs3/dev_flash" # Seems to be where the firmware is installed.
          ".config/rpcs3/input_configs" # Controller config.
          ".config/rpcs3/Icons" # Game icons.
        ];
        me.persist.files = [
          ".config/rpcs3/GuiConfigs/persistent_settings.dat" # play times and recently played
        ];
        me.state.directories = [ ".cache/rpcs3" ];

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