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

let
  steam_2s2h = pkgs.writeScriptBin "steam_2s2h" ''
    export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:${pkgs.libglvnd}/lib"
    exec ${pkgs._2ship2harkinian}/bin/2s2h "''${@}"
  '';
in
{
  imports = [ ];

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

  config = lib.mkIf config.me.ship2harkinian.enable (
    lib.mkMerge [
      {
        allowedUnfree = [ "2ship2harkinian" ];
      }
      (lib.mkIf config.me.graphical {
        home.packages = with pkgs; [
          _2ship2harkinian
          steam_2s2h
        ];

        home.file.".local/share/2ship/2ship2harkinian.json" = {
          source = ./files/2ship2harkinian.json;
        };

        me.persist.directories = [ ".local/share/2ship/saves" ];
        home.persistence."/home/deck/.state" = {
          files = [
            ".local/share/2ship/mm.o2r"
          ];
        };

        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._2ship2harkinian [
                    "-march=znver2"
                    "-mtune=znver2"
                  ])
                else
                  prev._2ship2harkinian;
            in
            {
              _2ship2harkinian = pkgs.buildEnv {
                name = prev._2ship2harkinian.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/2s2h.desktop
                '';
              };
            }
          )
        ];
      })
    ]
  );
}
