# checkm8 jailbreak CLI from upstream binaries; needs root. usbmuxd + idevice* help with USB iOS.
{ ... }: {
  flake.nixosModules.systemPalera1n =
    { config, lib, pkgs, ... }:
    let
      cfg = config.chiasson.system.palera1n;

      version = "2.2.1";

      srcFor =
        {
          x86_64-linux = pkgs.fetchurl {
            url = "https://github.com/palera1n/palera1n/releases/download/v${version}/palera1n-linux-x86_64";
            sha256 = "0l9ipabbiggkzvpy8hyi681kalln3z3396xsx4lz1393jw3c8dm2";
          };
          aarch64-linux = pkgs.fetchurl {
            url = "https://github.com/palera1n/palera1n/releases/download/v${version}/palera1n-linux-arm64";
            sha256 = "12n0136g218b5ndq2s7ssymab4i6pbb55l681b94zs9m9lvacfa1";
          };
        }
        .${pkgs.stdenv.hostPlatform.system} or null;

      palera1n =
        if srcFor == null then
          null
        else
          pkgs.stdenvNoCC.mkDerivation {
            pname = "palera1n";
            inherit version;
            src = srcFor;

            dontUnpack = true;

            installPhase = ''
              install -Dm755 $src $out/bin/palera1n
            '';

            meta = with lib; {
              description = "iOS jailbreak tool for checkm8 devices (A8–A11)";
              homepage = "https://palera.in";
              license = licenses.mit;
              sourceProvenance = with sourceTypes; [ binaryNativeCode ];
              platforms = [ "x86_64-linux" "aarch64-linux" ];
              mainProgram = "palera1n";
            };
          };
    in
    {
      options.chiasson.system.palera1n = {
        enable = lib.mkEnableOption ''
          palera1n from GitHub releases + usbmuxd / libimobiledevice toggles (defaults on).
        '';

        usbmuxd = {
          enable = lib.mkOption {
            type = lib.types.bool;
            default = true;
            description = "usbmuxd for iOS USB.";
          };
        };

        libimobiledevice = {
          enable = lib.mkOption {
            type = lib.types.bool;
            default = true;
            description = "idevice* tools on PATH.";
          };
        };
      };

      config = lib.mkIf cfg.enable (lib.mkMerge [
        (lib.mkIf (palera1n == null) {
          assertions = [
            {
              assertion = false;
              message = "system.palera1n: no upstream binary for ${pkgs.stdenv.hostPlatform.system}";
            }
          ];
        })
        (lib.mkIf (palera1n != null) {
          environment.systemPackages = [ palera1n ];
        })
        (lib.mkIf (cfg.enable && cfg.usbmuxd.enable) {
          services.usbmuxd.enable = true;
        })
        (lib.mkIf (cfg.enable && cfg.libimobiledevice.enable) {
          environment.systemPackages = [ pkgs.libimobiledevice ];
        })
      ]);
    };
}
