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

let
  steam_shipwright = pkgs.writeScriptBin "steam_soh" ''
    export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:${pkgs.libglvnd}/lib"
    exec ${pkgs.shipwright}/bin/soh "''${@}"
  '';
in
{
  imports = [ ];

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

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

        home.file.".local/share/soh/shipofharkinian.json" = {
          source = ./files/shipofharkinian.json;
        };

        me.persist.directories = [ ".local/share/soh/Save" ];
        home.persistence."/home/deck/.state" = {
          files = [
            ".local/share/soh/oot.otr"
          ];
        };

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