{ config, pkgs, lib, ... }:
let
  wine = pkgs.wineWowPackages.stable;
  dataDir  = "/var/lib/dr-server";
  buildDir = "${dataDir}/Build";
  prefix   = "${dataDir}/wine";
  logDir   = "${dataDir}/log";
in
{
  config = lib.mkIf (config.networking.hostName == "FredOS-Mediaserver") {
    users.users.dr-server = {
      isSystemUser = true;
      group = "dr-server";
      home = dataDir;
      description = "Dungeon Runners Reborn server";
    };
    users.groups.dr-server = {};

    systemd.tmpfiles.rules = [
      "d ${dataDir}  0750 dr-server dr-server -"
      "d ${buildDir} 0750 dr-server dr-server -"
      "d ${prefix}   0750 dr-server dr-server -"
      "d ${logDir}   0750 dr-server dr-server -"
    ];

    ## <----- DUNGEON RUNNERS REBORN ----> ##
    # Windows-only Unity build run headless under Wine. Initializes a
    # Win64 prefix on first boot via wineboot, then launches the exe
    # with Unity's batch flags. Only the friend's exe is in this tree —
    # the matching client is needed on connecting machines.
    systemd.services.dr-server = {
      description = "Dungeon Runners Reborn (Wine, headless Unity)";
      after = [ "network-online.target" ];
      wants = [ "network-online.target" ];
      wantedBy = [ "multi-user.target" ];

      path = [ wine pkgs.coreutils ];
      environment = {
        WINEPREFIX = prefix;
        WINEARCH = "win64";
        WINEDEBUG = "-all";
        HOME = dataDir;
      };

      preStart = ''
        if [ ! -f "${prefix}/system.reg" ]; then
          ${wine}/bin/wineboot --init
          ${wine}/bin/wineserver -w
        fi
      '';

      unitConfig.ConditionPathExists = "${buildDir}/DR_Server.exe";

      serviceConfig = {
        Type = "simple";
        User = "dr-server";
        Group = "dr-server";
        WorkingDirectory = buildDir;
        # Unity's Win64 build still tries to create a 1x1 hidden window
        # via Win32 even with -batchmode -nographics, and Wine needs a
        # real X display for that — fails with "Failed to create batch
        # mode window: Success." otherwise. xvfb-run gives it one.
        ExecStart = "${pkgs.xvfb-run}/bin/xvfb-run -a ${wine}/bin/wine64 DR_Server.exe -batchmode -nographics -logFile ${logDir}/server.log";
        Restart = "on-failure";
        RestartSec = "10s";
      };
    };

    networking.firewall.allowedTCPPorts = [ 2110 2603 2604 2605 2606 ];
    networking.firewall.allowedUDPPorts = [ 2110 2603 2604 2605 2606 ];
  };
}
