{
  pkgs,
  inputs,
  ...
}:
let
  wallpaper = "${inputs.self}/assets/wallpaper/wallpaper1.jpg";
  setWallpaperScript = pkgs.writeShellScriptBin "set-wallpaper-script" ''
    set -eu

    # System Events runs in the logged-in Aqua session and updates every Space.
    # Retry because launch agents can start before the desktop is fully ready.
    for attempt in {1..12}; do
      if /usr/bin/osascript <<'APPLESCRIPT'
        tell application "System Events"
          tell every desktop
            set picture to "${wallpaper}"
          end tell
        end tell
APPLESCRIPT
      then
        exit 0
      fi

      /bin/sleep 5
    done

    exit 1
  '';
in
{
  environment.systemPackages = [ setWallpaperScript ];

  launchd.user.agents.set-wallpaper = {
    command = "${setWallpaperScript}/bin/set-wallpaper-script";
    serviceConfig = {
      RunAtLoad = true;
      ProcessType = "Interactive";
      LimitLoadToSessionType = "Aqua";
    };
  };
}
