-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsquad-server.nix
1050 lines (968 loc) · 44.2 KB
/
squad-server.nix
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{ config, lib, pkgs, ... }:
let
cfg = config.services.squad-server;
settingsFormat = pkgs.formats.keyValue { };
replaceNonAlum = rep: str: (builtins.foldl' (x: y: if builtins.isString y then x + y else x + rep)
""
(builtins.split "[^[:alnum:]]" str));
in
{
options.services.squad-server = {
servers = lib.mkOption {
description = ''
The squad servers to create and run.
Defined as `servers.<name>`. By default the `<name>` will be used as the
`servers.<name>.config.server.settings.ServerName`.
'';
type = lib.types.attrsOf (lib.types.submodule ({ name, config, ... }: {
options = {
enable = lib.mkEnableOption "Enable Squad Server";
openFirewall = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
Whether to open ports in the firewall for the server.
'';
};
gamePort = lib.mkOption {
type = lib.types.port;
default = 7787;
apply = (port: [ port (port + 1) ]);
description = ''
The server's game port. This will open the port specified here and the `gamePort + 1` as
Squad needs both open.
'';
};
queryPort = lib.mkOption {
type = lib.types.port;
apply = (port: [ port (port + 1) ]);
default = 27165;
description = ''
The server's query port. This will open the port specified here and the `queryPort + 1` as
Squad needs both open.
'';
};
rconPort = lib.mkOption {
type = lib.types.port;
apply = (port: [ port ]);
default = 21114;
description = ''
The server's rcon port. This is needed for remote administration of the server.
'';
};
beaconPort = lib.mkOption {
type = lib.types.port;
apply = (port: [ port ]);
default = 15000;
description = ''
The server's Epic Online Services beacon port.
'';
};
stateDir = lib.mkOption {
type = lib.types.str;
default = "squad/${replaceNonAlum "_" name}";
description = ''
State directory for the systemd user service. This is where the Squad Server will be
installed to along with configuration.
'';
};
cacheDir = lib.mkOption {
type = lib.types.str;
default = "squad/${replaceNonAlum "_" name}";
description = ''
State directory for the systemd user service.
'';
};
mods = lib.mkOption {
# TODO: Better define requirements for a mod id beyond being a positive integer
type = lib.types.listOf lib.types.ints.positive;
default = [ ];
description = ''
A list of mods to install to the server via their ids.
A mod example would be `1959152751`, which is the Middle East Escalation mod for
Squad. It can be found at this link:
https://steamcommunity.com/sharedfiles/filedetails/?id=1959152751.
'';
};
config = {
rcon = {
settings = lib.mkOption {
description = ''
Options to be defined in Rcon.cfg.
See https://squad.fandom.com/wiki/Server_Configuration#Rcon_control_in_Rcon.cfg for more
details.
'';
default = { };
type = lib.types.submodule {
freeformType = settingsFormat.type;
options = {
Port = lib.mkOption {
type = lib.types.port;
default = builtins.elemAt config.rconPort 0;
visible = false;
readOnly = true;
description = ''
RCON port to define in the Rcon.cfg. This will always use the rcon port
defined in `rconPort`.
'';
};
IP = lib.mkOption {
type = lib.types.str;
default = "0.0.0.0";
description = ''
IP to bind the RCON socket to an alternate IP address.
'';
};
MaxConnections = lib.mkOption {
type = lib.types.ints.positive;
default = 5;
description = ''
Maximum number of allowable concurrent RCON connections
'';
};
Password = lib.mkOption {
type = lib.types.str;
default = "";
description = ''
The password to provide to RCON. If this is empty (default) then RCON is disabled.
Prefer the `config.rcon.passwordFile` option so the password is not copied into
the Nix Store.
'';
};
ConnectionTimeout = lib.mkOption {
type =
lib.types.addCheck lib.types.ints.unsigned (x: x <= 86400);
default = 300;
description = ''
Number of seconds without contact from a connected console before the server
checks to see if the session is still active or if it got disconnected. Supports
values between 0 and 86400 (1 day). Set to zero to disable the timeout.
'';
};
SecondsBeforeTimeoutCheck = lib.mkOption {
type = lib.types.addCheck lib.types.ints.positive
(x: x >= 30 && x <= 3600);
default = 120;
description = ''
Number of seconds without contact from a connected console before the server sends
a TCP KEEPALIVE to check if the session is still active or if it dog disconnected.
Supports values between 30 and 3600 (1 hour).
'';
};
AuthenticationTimeout = lib.mkOption {
type =
lib.types.addCheck lib.types.ints.unsigned (x: x <= 3600);
default = 5;
description = ''
Number of seconds the server will wait for the console to authenticate when a
connection has been established. Supports values between 0 and 3600 (1 hour). Set
to zero to disable the timeout.
'';
};
};
};
};
passwordFile = lib.mkOption {
type = lib.types.nullOr lib.types.path;
default = null;
description = "The file to read the rcon password from.";
};
};
admins = lib.mkOption {
description = ''
Groups to be defined in the Admin config along with users in the groups.
'';
default = { };
apply = groups: lib.attrsets.foldlAttrs
(acc: groupName: group: ''
${acc}${lib.optionalString (group.comment != null) ''
// ${lib.concatStringsSep "\n// " (lib.splitString "\n" (lib.removeSuffix "\n" group.comment))}''}
Group=${groupName}:${lib.concatStringsSep "," group.accessLevels}
${builtins.foldl' (acc: user: ''
${acc}Admin=${user.id}:${groupName} ${lib.optionalString (user.comment != null) "// ${user.comment}"}
'') "" group.members}
'') ""
groups;
type = lib.types.attrsOf (lib.types.submodule {
options = {
comment = lib.mkOption {
type = lib.types.nullOr lib.types.lines;
default = null;
description = ''
Optionally add a comment for the group in the Admin config.
'';
};
accessLevels = lib.mkOption {
type = lib.types.listOf (lib.types.enum [
"startvote"
"changemap"
"pause"
"cheat"
"private"
"balance"
"chat"
"kick"
"ban"
"config"
"cameraman"
"immune"
"manageserver"
"featuretest"
"reserve"
"demos"
"clientdemos"
"debug"
"teamchange"
"forceteamchange"
"canseeadminchat"
]);
default = [ ];
description = ''
A list of strings relating to valid access levels for admins in Squad's
admin config.
Valid access levels are:
startvote - Not used
changemap - Change the current map or set the next map
pause - Pause server gameplay
cheat - Use server cheat commands
private - Password protect server
balance - Group Ignores server team balance
chat - Admin chat and Server broadcast
kick - Kick players from the server
ban - Ban players from the server
config - Change server config
cameraman - Admin spectate mode
immune - Cannot be kicked / banned
manageserver - Shutdown server
featuretest - Any features added for testing by dev team
reserve - Reserve slot
demos - Record Demos on the server side via admin commands
clientdemos - Record Demos on the client side via commands or the replay UI.
debug - show admin stats command and other debugging info
teamchange - No timer limits on team change
forceteamchange - Can issue the ForceTeamChange command
canseeadminchat - This group can see the admin chat and teamkill/admin-join notifications
'';
};
members = lib.mkOption {
description = ''
Members that are in the group.
'';
default = [ ];
type = lib.types.listOf (lib.types.submodule {
options = {
# TODO: Improve constraints to ensure this is a steam64 id
id = lib.mkOption {
type = lib.types.ints.positive;
apply = (val: builtins.toString val);
description = ''
A user's steam64 id.
'';
};
comment = lib.mkOption {
type = lib.types.nullOr lib.types.singleLineStr;
default = null;
description = ''
Optionally add a comment for the user in the Admin config.
'';
};
};
});
};
};
});
};
bans = lib.mkOption {
type = lib.types.listOf lib.types.str;
apply = lib.concatStringsSep "\n";
default = [ ];
description = ''
Manual bans to add to the server configuration.
Basic Format: `<banned player steamid>:<unix timestamp of ban expiration>`.
For additional details see
https://squad.fandom.com/wiki/Server_Configuration#Bans_in_Bans.cfg.
'';
};
customOptions = lib.mkOption {
description = ''
Custom options for mods in key-value format. Note that seed settings are considered mod
settings for the purposes of Squad server configuration.
See https://squad.fandom.com/wiki/Server_Configuration#Custom_Options for more
details.
'';
default = { };
type = lib.types.submodule {
freeformType = settingsFormat.type;
options = {
SeedPlayersThreshold = lib.mkOption {
type = lib.types.ints.positive;
default = 50;
description = ''
Amount of players needed to start the pre-live countdown.
'';
};
SeedMinimumPlayersToLive = lib.mkOption {
type = lib.types.ints.positive;
default = 45;
description = ''
After reaching the SeedPlayersThreshold, if some players disconect, but the current
player count stays at or above this value, don't stop the pre-live countdown. Should
be less than SeedPlayersThreshold to be considered enabled.
'';
};
SeedMatchLengthSeconds = lib.mkOption {
type = lib.types.ints.positive;
default = 21600;
description = ''
Match length of a seed in seconds.
'';
};
SeedInitialTickets = lib.mkOption {
type = lib.types.ints.positive;
default = 100;
description = ''
Initial tickets for both teams.
'';
};
SeedAllKitsAvailable = lib.mkOption {
type = lib.types.bool;
default = true;
apply = (val: if val == true then 1 else 0);
description = ''
Enable or disable availability of all kits during seeding phase.
'';
};
SeedSecondsBeforeLive = lib.mkOption {
type = lib.types.float;
default = 60.0;
description = ''
Length of the pre-live countdown.
'';
};
};
};
};
excludedFactions = lib.mkOption {
type = lib.types.listOf lib.types.str;
apply = lib.concatStringsSep "\n";
default = [ ];
description = ''
Exlude factions from the rotation.
See https://squad.fandom.com/wiki/Server_Configuration#Excluded_Factions for more
details.
'';
};
excludedFactionSetups = lib.mkOption {
type = lib.types.listOf lib.types.str;
apply = lib.concatStringsSep "\n";
default = [ ];
description = ''
Exlude specific faction setups from the rotation.
See https://squad.fandom.com/wiki/Server_Configuration#Excluded_Faction_Setups for
more details.
'';
};
excludedLayers = lib.mkOption {
type = lib.types.listOf lib.types.str;
apply = lib.concatStringsSep "\n";
default = [ ];
description = ''
Exclude layers from loading.
See https://squad.fandom.com/wiki/Server_Configuration#Excluded_Layers for
more details.
'';
};
excludedLevels = lib.mkOption {
type = lib.types.listOf lib.types.str;
apply = lib.concatStringsSep "\n";
default = [ ];
description = ''
Exclude entire maps/levels from loading.
See https://squad.fandom.com/wiki/Server_Configuration#Excluded_Levels for
more details.
'';
};
levelRotation = lib.mkOption {
type = lib.types.listOf lib.types.str;
apply = lib.concatStringsSep "\n";
default = [ ];
description = ''
Set rotation of maps/levels allowing any layer on those maps.
See https://squad.fandom.com/wiki/Server_Configuration#Level_Rotation for
more details.
'';
};
layerRotation = lib.mkOption {
type = lib.types.listOf lib.types.str;
apply = lib.concatStringsSep "\n";
default = [ ];
description = ''
Set rotation of specific layers.
See https://squad.fandom.com/wiki/Server_Configuration#Layer_Rotation for
more details.
'';
};
serverMessages = lib.mkOption {
type = lib.types.listOf lib.types.str;
apply = lib.concatStringsSep "\n";
default = [ ];
description = ''
Server messages to show on a rotation based on the ServerMessageInterval.
See
https://squad.fandom.com/wiki/Server_Configuration#Server_Messages_in_ServerMessages.cfg
for more details.
'';
};
motd = lib.mkOption {
type = lib.types.lines;
default = "";
description = ''
Message to show to all players who join the server.
See https://squad.fandom.com/wiki/Server_Configuration#Message_of_the_day_in_Motd.cfg
for more details.
'';
};
remoteAdminLists = lib.mkOption {
type = lib.types.listOf lib.types.str;
apply = lib.concatStringsSep "\n";
default = [ ];
description = ''
The remote admin lists that the server will also pull from for admins.
See
https://squad.fandom.com/wiki/Server_Configuration#Remote_Admin_Lists_in_RemoteAdminListHosts.cfg
for more details.
'';
};
remoteBanLists = lib.mkOption {
type = lib.types.listOf lib.types.str;
apply = lib.concatStringsSep "\n";
default = [ ];
description = ''
The remote ban lists that the server will also pull from for bans.
See
https://squad.fandom.com/wiki/Server_Configuration#Remote_Ban_Lists_in_RemoteBanListHosts.cfg
for more details.
'';
};
server = {
passwordFile = lib.mkOption {
type = lib.types.nullOr lib.types.path;
default = null;
description = ''
The file to read the server password from. If this is set then the server will
require a password. Prefer this option over `ServerPassword`.
'';
};
maxTickRate = lib.mkOption {
type = lib.types.ints.positive;
default = 35;
description = ''
The max tick rate the server will run at. Recommended to use a tick rate of 35 (the
default).
'';
};
settings = lib.mkOption {
type = lib.types.submodule {
freeformType = settingsFormat.type;
options = {
ServerName = lib.mkOption {
type = lib.types.str;
default = "${name}";
description = ''
Server name of the server to show in the server browser.
Multiple servers MUST have unique names.
'';
};
ServerPassword = lib.mkOption {
type = lib.types.str;
default = "";
description = ''
The password required to join the server. If this is empty (defualt) then the
server will be joinable without a password. Prefer the
`config.server.passwordFile` option so the password is not copied into the Nix
Store.
'';
};
ShouldAdvertise = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Whether or not the server should appear in the server browser.
'';
};
IsLANMatch = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
Set the server to LAN mode.
'';
};
MaxPlayers = lib.mkOption {
type = lib.types.ints.positive;
# By default most licensed servers allow up to 100 players.
default = 100;
description = ''
Set the player limit for the server.
'';
};
NumReservedSlots = lib.mkOption {
type = lib.types.ints.positive;
default = 2;
description = ''
Set the number of reserved slots for those with `reserve` perms in the admin list.
'';
};
PublicQueueLimit = lib.mkOption {
type = lib.types.addCheck lib.types.int (x: x >= -1);
default = 25;
description = ''
The limit on how many players can be queued to join the server.
If set to -1 then the queue is unlimited.
'';
};
MapRotationMode = lib.mkOption {
type = lib.types.enum [
"LevelList"
"LayerList"
"LevelList_Randomized"
"LayerList_Randomized"
];
default = "LayerList";
description = ''
The map rotation mode to use. If set to LevelList, will use level rotation, if set
to LayerList, will use layer rotation. Suffixing with `_Randomized` will respect
the defined layers/levels, but not their ordering.
See https://squad.fandom.com/wiki/Server_Configuration#Map_Rotation_Modes for more
details.
'';
};
RandomizeAtStart = lib.mkOption {
type = lib.types.bool;
default = false;
readOnly = true;
visible = false;
description = ''
Whether the Map/Layer rotations list should be randomized at start.
According to Squad Configs "DO NOT USE, MODDED WILL NOT WORK".
'';
};
UseVoteFactions = lib.mkOption {
type = lib.types.bool;
default = false;
readOnly = true;
visible = false;
description = ''
Whether the Faction should be voted on at the end of a round.
At the time this was created, Squad's voting system does not work.
'';
};
UseVoteLevel = lib.mkOption {
type = lib.types.bool;
default = false;
readOnly = true;
visible = false;
description = ''
Whether the level should be voted on at the end of a round.
At the time this was created, Squad's voting system does not work.
'';
};
UseVoteLayer = lib.mkOption {
type = lib.types.bool;
default = false;
readOnly = true;
visible = false;
description = ''
Whether the layer should be voted on at the end of a round.
At the time this was created, Squad's voting system does not work.
'';
};
AllowTeamChanges = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Completely Allow or Disallow team changes to all players. Only users in the admin
config with `Level_Balance` can bypass this.
'';
};
PreventTeamChangeIfUnbalanced = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
If disabled, players can always change teams regardless of the balance.
'';
};
NumPlayersDiffForTeamChanges = lib.mkOption {
type = lib.types.ints.unsigned;
default = 2;
description = ''
Maximum allowed difference in player count between teams. This takes into account
the team the player leaves and the team the player joins.
'';
};
RejoinSquadDelayAfterKick = lib.mkOption {
type = lib.types.ints.unsigned;
default = 180;
description = ''
Amount of time before a player kicked from a squad can rejoin that squad.
'';
};
RecordDemos = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
Allow admins with `ClientDemos` permission to record demos. It's recommended to
leave this disabled as it can be used to cheat easily without a way to detect if
cheating is occuring.
'';
};
AllowPublicClientsToRecord = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
Allow any playersto record demos. It's recommended to leave this disabled as it
can be used to cheat easily without a way to detect if cheating is occuring.
'';
};
ServerMessageInterval = lib.mkOption {
type = lib.types.ints.positive;
default = 1200;
description = ''
Interval between showing server messages.
'';
};
TKAutoKickEnabled = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Whether or not to kick players who exceed the `AutoTKBanNumberTKs` limit.
NOTE: Licensed servers MUST enable this option.
'';
};
AutoTKBanNumberTKs = lib.mkOption {
type = lib.types.ints.positive;
default = 10;
description = ''
How many TKs a player may have before being kicked.
NOTE: Licensed servers MUST set this option between 7 and 10 inclusive.
'';
};
AutoTKBanTime = lib.mkOption {
type = lib.types.ints.unsigned;
default = 300;
description = ''
How long to reject a player auto kicked for TKs from joining in seconds.
NOTE: Licensed servers MUST set this option to be more than 0.
'';
};
AllowDevProfiling = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Whether to allow Offword Industries Developers to be admins in the server.
NOTE: Licensed servers MUST enable this option.
'';
};
VehicleClaimingDisabled = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
Whether to disable vehicle claiming.
NOTE: Licensed servers MUST disable this option.
'';
};
Tags = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
apply = lib.concatStringsSep " ";
description = ''
Tags to apply to the server to be shown in the server browser.
See https://squad.fandom.com/wiki/Server_Configuration#Tag_System for more details.
'';
};
Rules = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
apply = lib.concatStringsSep " ";
description = ''
Rules to apply to the server to be shown in the server browser.
See https://squad.fandom.com/wiki/Server_Configuration#Tag_System for more details.
'';
};
};
};
default = { };
description = ''
Options to be defined in Server.cfg
See
https://squad.fandom.com/wiki/Server_Configuration#Server_Configuration_Settings_in_Server.cfg
for more details.
'';
};
};
license = {
file = lib.mkOption {
type = lib.types.nullOr lib.types.path;
default = null;
description = ''
A path to a file containing the server license. Prefer this over
`config.license.content` so the license text isn't copied into the Nix
store.
'';
};
content = lib.mkOption {
type = lib.types.str;
default = "";
description = ''
The raw content of the license for the server. Prefer using the
`config.license.file` option over this as the content in this option will be copied
into the Nix store.
'';
};
};
};
};
}));
};
};
config =
let
# Credit to https://github.com/mkaito/nixos-modded-minecraft-servers/tree/master.
# A fair bit of the handling of the nested servers was based upon the code there.
enabledServers = lib.filterAttrs (_: conf: conf.enable) cfg.servers;
mkServerName = name: "squad-${replaceNonAlum "-" name}";
eachEnabledServer = f: lib.mapAttrs' (name: config: lib.nameValuePair (mkServerName name) (f name config)) enabledServers;
collectPorts = portType: lib.lists.flatten (lib.mapAttrsToList (_: serverConfig: serverConfig.${portType}) enabledServers);
gamePorts = collectPorts "gamePort";
queryPorts = collectPorts "queryPort";
rconPorts = collectPorts "rconPort";
beaconPorts = collectPorts "beaconPort";
allPorts = gamePorts ++ queryPorts ++ rconPorts ++ beaconPorts;
in
{
assertions = [
{
assertion = (lib.unique gamePorts) == gamePorts;
message = ''
Your Squad servers have overlapping game ports. Ensure the game ports are unique.
Reminder: Squad uses the game port you define and `gamePort + 1`.
Game Ports Found:
${builtins.toJSON gamePorts}
'';
}
{
assertion = (lib.unique queryPorts) == queryPorts;
message = ''
Your Squad servers have overlapping query ports. Ensure the query ports are unique.
Reminder: Squad uses the query port you define and `queryPort + 1`.
Query Ports Found:
${builtins.toJSON queryPorts}
'';
}
{
assertion = (lib.unique rconPorts) == rconPorts;
message = ''
Your Squad servers have overlapping rcon ports. Ensure the rcon ports are unique.
Rcon Ports Found:
${builtins.toJSON rconPorts}
'';
}
{
assertion = (lib.unique beaconPorts) == beaconPorts;
message = ''
Your Squad servers have overlapping beacon ports. Ensure the beacon ports are unique.
Rcon Ports Found:
${builtins.toJSON beaconPorts}
'';
}
{
assertion = (lib.unique allPorts) == allPorts;
message = ''
Your Squad servers have overlapping ports among game, query, rcon, and beacon ports.
Ensure all ports are unique among all Squad servers.
All Ports Found:
${builtins.toJSON allPorts}
'';
}
];
networking.firewall = {
allowedUDPPorts = beaconPorts ++ gamePorts ++ queryPorts ++ rconPorts;
allowedTCPPorts = rconPorts ++ queryPorts;
};
systemd.services = (eachEnabledServer (name: cfg:
let
cfgs = {
Admins = pkgs.writeText "Admins.cfg" cfg.config.admins;
Bans = pkgs.writeText "Bans.cfg" cfg.config.bans;
CustomOptions = settingsFormat.generate "CustomOptions.cfg" cfg.config.customOptions;
ExcludedFactionSetups = pkgs.writeText "ExcludedFactionSetups.cfg" cfg.config.excludedFactionSetups;
ExcludedFactions = pkgs.writeText "ExcludedFactions.cfg" cfg.config.excludedFactions;
ExcludedLayers = pkgs.writeText "ExcludedLayers.cfg" cfg.config.excludedLayers;
ExcludedLevels = pkgs.writeText "ExcludedLevels.cfg" cfg.config.excludedLevels;
LayerRotation = pkgs.writeText "LayerRotation.cfg" cfg.config.layerRotation;
LevelRotation = pkgs.writeText "LayerRotation.cfg" cfg.config.levelRotation;
License = pkgs.writeText "License.cfg" cfg.config.license.content;
MOTD = pkgs.writeText "MOTD.cfg" cfg.config.motd;
Rcon = settingsFormat.generate "Rcon.cfg" cfg.config.rcon.settings;
RemoteAdminListHosts = pkgs.writeText "RemoteAdminListHosts.cfg" cfg.config.remoteAdminLists;
RemoteBanListHosts = pkgs.writeText "RemoteBanListHosts.cfg" cfg.config.remoteBanLists;
Server = settingsFormat.generate "Server.cfg" cfg.config.server.settings;
ServerMessages = pkgs.writeText "ServerMessages.cfg" cfg.config.serverMessages;
};
in
{
wantedBy = [ "multi-user.target" ];
serviceConfig = {
DynamicUser = true;
StateDirectory = "${cfg.stateDir}";
CacheDirectory = "${cfg.cacheDir}";
StateDirectoryMode = "0700";
LoadCredential = [ ]
++
lib.optional
(cfg.config.rcon.passwordFile != null)
[ "SQUAD_RCON_PASSWORD_FILE:${cfg.config.rcon.passwordFile}" ]
++
lib.optional
(cfg.config.server.passwordFile != null)
[ "SQUAD_SERVER_PASSWORD_FILE:${cfg.config.server.passwordFile}" ]
++
lib.optional
(cfg.config.license.file != null)
[ "SQUAD_LICENSE_FILE:${cfg.config.license.file}" ];
ExecStart =
let
server_dir = "/var/lib/${cfg.stateDir}";
in
pkgs.writeScript "start-squad-server" ''
#!${pkgs.bash}/bin/bash
set -euo pipefail
# Install or update the server.
cat <<-__EOS__
┌
│ Installing/Updating Squad Server:
│ Name -> '${cfg.config.server.settings.ServerName}'
│ Path -> '${server_dir}'
│
│ This may take a while as the server will need to download any required files if they
│ weren't downloaded previously.
└
__EOS__
HOME="/var/cache/${cfg.cacheDir}" ${pkgs.steamcmd}/bin/steamcmd \
+force_install_dir "${server_dir}" \
+login anonymous \
+app_update 403240 validate \
+quit
# Install mods if any are defined
${let
workshop_id = "393380";
mod_install_dir = "${server_dir}/steamapps/workshop/content/${workshop_id}";
in
lib.optionalString (builtins.length (cfg.mods) > 0) ''
cat <<-__EOS__
┌
│ Installing Mods for Squad Server:
│ Mod IDs -> ${builtins.toString cfg.mods}
│
│ This may take a while as the server will need to download any required files if they
│ weren't downloaded previously.
└
__EOS__
read -ra SQUAD_MODS <<< "${builtins.toString cfg.mods}"
for mod in "''${SQUAD_MODS[@]}"; do
printf "==== Attempting to install mod: '%s' ====\n" "$mod"
# We have to do this attempt stuff because steamcmd can timeout while downloading
# large mods. By making another attempt steamcmd will continue downloading from
# where it left off. From experience it should need no more than 5 attempts. Any
# more than that and either steam is getting DoS'd, you've been rate limited
# completely, your network is *way* too slow, or nuclear war has been declared and
# all that remains of AWS east is a crater.
REMAINING_ATTEMPTS=5
until HOME="/var/cache/${cfg.cacheDir}" ${pkgs.steamcmd}/bin/steamcmd \
+force_install_dir "${mod_install_dir}/$mod" \
+login anonymous \
+workshop_download_item "${workshop_id}" "$mod" \
+quit; do
(( REMAINING_ATTEMPTS-- ))
printf "Did not fully download squad mod '%s', remaining attempts: '%s'\n" \
"$mod" "$REMAINING_ATTEMPTS"
if (( REMAINING_ATTEMPTS == 0 )); then
printf "#### Too many attempts while downloading a mod! Failed to download the mod: '%s' ####\n" "$mod"
exit 1
fi
done
ln -sf "${mod_install_dir}/$mod" "${server_dir}/SquadGame/Plugins/Mods/$mod"
printf "#### Successfully installed mod: '%s' ####\n" "$mod"
done
''}
cat <<-__EOS__
┌
│ Patching Squad Binaries
└
__EOS__
find "${server_dir}/" \
-type f \
-executable \
-printf "patchelf: Attempting to patch '%p'\n" \
-exec \
${pkgs.patchelf}/bin/patchelf --set-interpreter ${pkgs.glibc}/lib/ld-linux-x86-64.so.2 {} \;
cat <<-__EOS__
┌
│ Generating Configurations
└
__EOS__
pushd ./SquadGame/ServerConfig >/dev/null 2>&1
${lib.attrsets.foldlAttrs (acc: name: path: ''
${acc}
# Handle the ${name} configuration
printf "Generating the '%s' configuration file.\n" "${name}.cfg"
cp -f "${path}" ./"${name}.cfg"'') "" cfgs}
${lib.optionalString (cfg.config.server.passwordFile != null) ''
## Handle secrets for the `Server.cfg` file ##
# Safely load the server password outside of the nix store
while read -r line; do
if [[ "$line" == ServerPassword=* ]]; then
echo "ServerPassword=$(${pkgs.systemd}/bin/systemd-creds cat SQUAD_SERVER_PASSWORD_FILE)"