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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
//! # Implementing new commands.
//! To implement a new command provide a handler function
//! in [do_command].

use crate::{
    client::Client,
    location::Locations,
    login_provider::LoginProvider,
    presence::Presence,
    settings::{
        Ban, BanAction, BanInfo, EditableSetting, SettingError, WhitelistInfo, WhitelistRecord,
    },
    sys::terrain::NpcData,
    weather::WeatherSim,
    wiring,
    wiring::OutputFormula,
    Server, Settings, SpawnPoint, StateExt,
};
use assets::AssetExt;
use authc::Uuid;
use chrono::{NaiveTime, Timelike, Utc};
use common::{
    assets,
    calendar::Calendar,
    cmd::{
        KitSpec, ServerChatCommand, BUFF_PACK, BUFF_PARSER, ITEM_SPECS, KIT_MANIFEST_PATH,
        PRESET_MANIFEST_PATH,
    },
    comp::{
        self,
        aura::{Aura, AuraKind, AuraTarget},
        buff::{Buff, BuffCategory, BuffData, BuffKind, BuffSource},
        inventory::item::{tool::AbilityMap, MaterialStatManifest, Quality},
        invite::InviteKind,
        AdminRole, ChatType, Inventory, Item, LightEmitter, WaypointArea,
    },
    depot,
    effect::Effect,
    event::{EventBus, ServerEvent},
    generation::{EntityConfig, EntityInfo},
    link::Is,
    mounting::Rider,
    npc::{self, get_npc_name},
    outcome::Outcome,
    parse_cmd_args,
    resources::{BattleMode, PlayerPhysicsSettings, Time, TimeOfDay},
    terrain::{Block, BlockKind, SpriteKind, TerrainChunkSize},
    uid::{Uid, UidAllocator},
    vol::{ReadVol, RectVolSize},
    weather, Damage, DamageKind, DamageSource, Explosion, LoadoutBuilder, RadiusEffect,
};
use common_net::{
    msg::{DisconnectReason, Notification, PlayerListUpdate, PresenceKind, ServerGeneral},
    sync::WorldSyncExt,
};
use common_state::{BuildAreaError, BuildAreas};
use core::{cmp::Ordering, convert::TryFrom, time::Duration};
use hashbrown::{HashMap, HashSet};
use humantime::Duration as HumanDuration;
use rand::{thread_rng, Rng};
use specs::{
    saveload::MarkerAllocator, storage::StorageEntry, Builder, Entity as EcsEntity, Join, WorldExt,
};
use std::{fmt::Write, str::FromStr, sync::Arc};
use vek::*;
use wiring::{Circuit, Wire, WireNode, WiringAction, WiringActionEffect, WiringElement};
use world::util::{Sampler, LOCALITY};

use common::comp::Alignment;
use tracing::{error, info, warn};

pub trait ChatCommandExt {
    fn execute(&self, server: &mut Server, entity: EcsEntity, args: Vec<String>);
}
impl ChatCommandExt for ServerChatCommand {
    fn execute(&self, server: &mut Server, entity: EcsEntity, args: Vec<String>) {
        if let Err(err) = do_command(server, entity, entity, args, self) {
            server.notify_client(
                entity,
                ServerGeneral::server_msg(ChatType::CommandError, err),
            );
        }
    }
}

type CmdResult<T> = Result<T, String>;

/// Handler function called when the command is executed.
/// # Arguments
/// * `&mut Server` - the `Server` instance executing the command.
/// * `EcsEntity` - an `Entity` corresponding to the player that invoked the
///   command.
/// * `EcsEntity` - an `Entity` for the player on whom the command is invoked.
///   This differs from the previous argument when using /sudo
/// * `Vec<String>` - a `Vec<String>` containing the arguments of the command
///   after the keyword.
/// * `&ChatCommand` - the command to execute with the above arguments.
/// Handler functions must parse arguments from the the given `String`
/// (`parse_args!` exists for this purpose).
///
/// # Returns
///
/// A `Result` that is `Ok` if the command went smoothly, and `Err` if it
/// failed; on failure, the string is sent to the client who initiated the
/// command.
type CommandHandler =
    fn(&mut Server, EcsEntity, EcsEntity, Vec<String>, &ServerChatCommand) -> CmdResult<()>;

fn do_command(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    cmd: &ServerChatCommand,
) -> CmdResult<()> {
    // Make sure your role is at least high enough to execute this command.
    if cmd.needs_role() > server.entity_admin_role(client) {
        return Err(format!(
            "You don't have permission to use '/{}'.",
            cmd.keyword()
        ));
    }

    let handler: CommandHandler = match cmd {
        ServerChatCommand::Adminify => handle_adminify,
        ServerChatCommand::Airship => handle_spawn_airship,
        ServerChatCommand::Alias => handle_alias,
        ServerChatCommand::ApplyBuff => handle_apply_buff,
        ServerChatCommand::Ban => handle_ban,
        ServerChatCommand::BattleMode => handle_battlemode,
        ServerChatCommand::BattleModeForce => handle_battlemode_force,
        ServerChatCommand::Body => handle_body,
        ServerChatCommand::Build => handle_build,
        ServerChatCommand::BuildAreaAdd => handle_build_area_add,
        ServerChatCommand::BuildAreaList => handle_build_area_list,
        ServerChatCommand::BuildAreaRemove => handle_build_area_remove,
        ServerChatCommand::Campfire => handle_spawn_campfire,
        ServerChatCommand::DebugColumn => handle_debug_column,
        ServerChatCommand::DebugWays => handle_debug_ways,
        ServerChatCommand::DisconnectAllPlayers => handle_disconnect_all_players,
        ServerChatCommand::DropAll => handle_drop_all,
        ServerChatCommand::Dummy => handle_spawn_training_dummy,
        ServerChatCommand::Explosion => handle_explosion,
        ServerChatCommand::Faction => handle_faction,
        ServerChatCommand::GiveItem => handle_give_item,
        ServerChatCommand::Goto => handle_goto,
        ServerChatCommand::Group => handle_group,
        ServerChatCommand::GroupInvite => handle_group_invite,
        ServerChatCommand::GroupKick => handle_group_kick,
        ServerChatCommand::GroupLeave => handle_group_leave,
        ServerChatCommand::GroupPromote => handle_group_promote,
        ServerChatCommand::Health => handle_health,
        ServerChatCommand::Help => handle_help,
        ServerChatCommand::Home => handle_home,
        ServerChatCommand::JoinFaction => handle_join_faction,
        ServerChatCommand::Jump => handle_jump,
        ServerChatCommand::Kick => handle_kick,
        ServerChatCommand::Kill => handle_kill,
        ServerChatCommand::KillNpcs => handle_kill_npcs,
        ServerChatCommand::Kit => handle_kit,
        ServerChatCommand::Lantern => handle_lantern,
        ServerChatCommand::Light => handle_light,
        ServerChatCommand::MakeBlock => handle_make_block,
        ServerChatCommand::MakeNpc => handle_make_npc,
        ServerChatCommand::MakeSprite => handle_make_sprite,
        ServerChatCommand::Motd => handle_motd,
        ServerChatCommand::Object => handle_object,
        ServerChatCommand::PermitBuild => handle_permit_build,
        ServerChatCommand::Players => handle_players,
        ServerChatCommand::Region => handle_region,
        ServerChatCommand::ReloadChunks => handle_reload_chunks,
        ServerChatCommand::RemoveLights => handle_remove_lights,
        ServerChatCommand::RevokeBuild => handle_revoke_build,
        ServerChatCommand::RevokeBuildAll => handle_revoke_build_all,
        ServerChatCommand::Safezone => handle_safezone,
        ServerChatCommand::Say => handle_say,
        ServerChatCommand::ServerPhysics => handle_server_physics,
        ServerChatCommand::SetMotd => handle_set_motd,
        ServerChatCommand::Ship => handle_spawn_ship,
        ServerChatCommand::Site => handle_site,
        ServerChatCommand::SkillPoint => handle_skill_point,
        ServerChatCommand::SkillPreset => handle_skill_preset,
        ServerChatCommand::Spawn => handle_spawn,
        ServerChatCommand::Sudo => handle_sudo,
        ServerChatCommand::Tell => handle_tell,
        ServerChatCommand::Time => handle_time,
        ServerChatCommand::Tp => handle_tp,
        ServerChatCommand::Unban => handle_unban,
        ServerChatCommand::Version => handle_version,
        ServerChatCommand::Waypoint => handle_waypoint,
        ServerChatCommand::Wiring => handle_spawn_wiring,
        ServerChatCommand::Whitelist => handle_whitelist,
        ServerChatCommand::World => handle_world,
        ServerChatCommand::MakeVolume => handle_make_volume,
        ServerChatCommand::Location => handle_location,
        ServerChatCommand::CreateLocation => handle_create_location,
        ServerChatCommand::DeleteLocation => handle_delete_location,
        ServerChatCommand::WeatherZone => handle_weather_zone,
        ServerChatCommand::Lightning => handle_lightning,
    };

    handler(server, client, target, args, cmd)
}

// Fallibly get position of entity with the given descriptor (used for error
// message).
fn position(server: &Server, entity: EcsEntity, descriptor: &str) -> CmdResult<comp::Pos> {
    server
        .state
        .ecs()
        .read_storage::<comp::Pos>()
        .get(entity)
        .copied()
        .ok_or_else(|| format!("Cannot get position for {:?}!", descriptor))
}

fn position_mut<T>(
    server: &mut Server,
    entity: EcsEntity,
    descriptor: &str,
    f: impl for<'a> FnOnce(&'a mut comp::Pos) -> T,
) -> CmdResult<T> {
    let entity = server
        .state
        .ecs()
        .read_storage::<Is<Rider>>()
        .get(entity)
        .and_then(|is_rider| {
            server
                .state
                .ecs()
                .read_resource::<UidAllocator>()
                .retrieve_entity_internal(is_rider.mount.into())
        })
        .unwrap_or(entity);

    let mut maybe_pos = None;

    let res = server
        .state
        .ecs()
        .write_storage::<comp::Pos>()
        .get_mut(entity)
        .map(|pos| {
            let res = f(pos);
            maybe_pos = Some(pos.0);
            res
        })
        .ok_or_else(|| format!("Cannot get position for {:?}!", descriptor));

    if let Some(pos) = maybe_pos {
        if server
            .state
            .ecs()
            .read_storage::<Presence>()
            .get(entity)
            .map(|presence| presence.kind == PresenceKind::Spectator)
            .unwrap_or(false)
        {
            server.notify_client(entity, ServerGeneral::SpectatePosition(pos));
        } else {
            server
                .state
                .ecs()
                .write_storage::<comp::ForceUpdate>()
                .get_mut(entity)
                .map(|force_update| force_update.update());
        }
    }
    res
}

fn insert_or_replace_component<C: specs::Component>(
    server: &mut Server,
    entity: EcsEntity,
    component: C,
    descriptor: &str,
) -> CmdResult<()> {
    server
        .state
        .ecs_mut()
        .write_storage()
        .insert(entity, component)
        .and(Ok(()))
        .map_err(|_| format!("Entity {:?} is dead!", descriptor))
}

fn uuid(server: &Server, entity: EcsEntity, descriptor: &str) -> CmdResult<Uuid> {
    server
        .state
        .ecs()
        .read_storage::<comp::Player>()
        .get(entity)
        .map(|player| player.uuid())
        .ok_or_else(|| format!("Cannot get player information for {:?}", descriptor))
}

fn real_role(server: &Server, uuid: Uuid, descriptor: &str) -> CmdResult<AdminRole> {
    server
        .editable_settings()
        .admins
        .get(&uuid)
        .map(|record| record.role.into())
        .ok_or_else(|| format!("Cannot get administrator roles for {:?} uuid", descriptor))
}

// Fallibly get uid of entity with the given descriptor (used for error
// message).
fn uid(server: &Server, target: EcsEntity, descriptor: &str) -> CmdResult<Uid> {
    server
        .state
        .ecs()
        .read_storage::<Uid>()
        .get(target)
        .copied()
        .ok_or_else(|| format!("Cannot get uid for {:?}", descriptor))
}

fn area(server: &mut Server, area_name: &str) -> CmdResult<depot::Id<Aabb<i32>>> {
    server
        .state
        .mut_resource::<BuildAreas>()
        .area_names()
        .get(area_name)
        .copied()
        .ok_or_else(|| format!("Area name not found: {}", area_name))
}

// Prevent use through sudo.
fn no_sudo(client: EcsEntity, target: EcsEntity) -> CmdResult<()> {
    if client == target {
        Ok(())
    } else {
        // This happens when [ab]using /sudo
        Err("It's rude to impersonate people".into())
    }
}

/// Ensure that client role is above target role, for the purpose of performing
/// some (often permanent) administrative action on the target.  Note that this
/// function is *not* a replacement for actually verifying that the client
/// should be able to execute the command at all, which still needs to be
/// rechecked, nor does it guarantee that either the client or the target
/// actually have an entry in the admin settings file.
///
/// For our purposes, there are *two* roles--temporary role, and permanent role.
/// For the purpose of these checks, currently *any* permanent role overrides
/// *any* temporary role (this may change if more roles are added that aren't
/// moderator or administrator).  If the permanent roles match, the temporary
/// roles are used as a tiebreaker.  /adminify should ensure that no one's
/// temporary role can be different from their permanent role without someone
/// with a higher role than their permanent role allowing it, and only permanent
/// roles should be recorded in the settings files.
fn verify_above_role(
    server: &mut Server,
    (client, client_uuid): (EcsEntity, Uuid),
    (player, player_uuid): (EcsEntity, Uuid),
    reason: &str,
) -> CmdResult<()> {
    let client_temp = server.entity_admin_role(client);
    let client_perm = server
        .editable_settings()
        .admins
        .get(&client_uuid)
        .map(|record| record.role);

    let player_temp = server.entity_admin_role(player);
    let player_perm = server
        .editable_settings()
        .admins
        .get(&player_uuid)
        .map(|record| record.role);

    if client_perm > player_perm || client_perm == player_perm && client_temp > player_temp {
        Ok(())
    } else {
        Err(reason.into())
    }
}

fn find_alias(ecs: &specs::World, alias: &str) -> CmdResult<(EcsEntity, Uuid)> {
    (&ecs.entities(), &ecs.read_storage::<comp::Player>())
        .join()
        .find(|(_, player)| player.alias == alias)
        .map(|(entity, player)| (entity, player.uuid()))
        .ok_or_else(|| format!("Player {:?} not found!", alias))
}

fn find_uuid(ecs: &specs::World, uuid: Uuid) -> CmdResult<EcsEntity> {
    (&ecs.entities(), &ecs.read_storage::<comp::Player>())
        .join()
        .find(|(_, player)| player.uuid() == uuid)
        .map(|(entity, _)| entity)
        .ok_or_else(|| format!("Player with UUID {:?} not found!", uuid))
}

fn find_username(server: &mut Server, username: &str) -> CmdResult<Uuid> {
    server
        .state
        .mut_resource::<LoginProvider>()
        .username_to_uuid(username)
        .map_err(|_| format!("Unable to determine UUID for username {:?}", username))
}

/// NOTE: Intended to be run only on logged-in clients.
fn uuid_to_username(
    server: &mut Server,
    fallback_entity: EcsEntity,
    uuid: Uuid,
) -> CmdResult<String> {
    let make_err = || format!("Unable to determine username for UUID {:?}", uuid);
    let player_storage = server.state.ecs().read_storage::<comp::Player>();

    let fallback_alias = &player_storage
        .get(fallback_entity)
        .ok_or_else(make_err)?
        .alias;

    server
        .state
        .ecs()
        .read_resource::<LoginProvider>()
        .uuid_to_username(uuid, fallback_alias)
        .map_err(|_| make_err())
}

fn edit_setting_feedback<S: EditableSetting>(
    server: &mut Server,
    client: EcsEntity,
    result: Option<(String, Result<(), SettingError<S>>)>,
    failure: impl FnOnce() -> String,
) -> CmdResult<()> {
    let (info, result) = result.ok_or_else(failure)?;
    match result {
        Ok(()) => {
            server.notify_client(
                client,
                ServerGeneral::server_msg(ChatType::CommandInfo, info),
            );
            Ok(())
        },
        Err(SettingError::Io(err)) => {
            warn!(
                ?err,
                "Failed to write settings file to disk, but succeeded in memory (success message: \
                 {})",
                info,
            );
            server.notify_client(
                client,
                ServerGeneral::server_msg(
                    ChatType::CommandError,
                    format!(
                        "Failed to write settings file to disk, but succeeded in memory.\n
                            Error (storage): {:?}\n
                            Success (memory): {}",
                        err, info
                    ),
                ),
            );
            Ok(())
        },
        Err(SettingError::Integrity(err)) => Err(format!(
            "Encountered an error while validating the request: {:?}",
            err
        )),
    }
}

fn handle_drop_all(
    server: &mut Server,
    _client: EcsEntity,
    target: EcsEntity,
    _args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    let pos = position(server, target, "target")?;

    let mut items = Vec::new();
    if let Some(mut inventory) = server
        .state
        .ecs()
        .write_storage::<Inventory>()
        .get_mut(target)
    {
        items = inventory.drain().collect();
    }

    let mut rng = thread_rng();

    let item_to_place = items
        .into_iter()
        .filter(|i| !matches!(i.quality(), Quality::Debug));
    for item in item_to_place {
        let vel = Vec3::new(rng.gen_range(-0.1..0.1), rng.gen_range(-0.1..0.1), 0.5);

        server
            .state
            .create_item_drop(Default::default(), item)
            .with(comp::Pos(Vec3::new(
                pos.0.x + rng.gen_range(5.0..10.0),
                pos.0.y + rng.gen_range(5.0..10.0),
                pos.0.z + 5.0,
            )))
            .with(comp::Vel(vel))
            .build();
    }

    Ok(())
}

fn handle_give_item(
    server: &mut Server,
    _client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    if let (Some(item_name), give_amount_opt) = parse_cmd_args!(args, String, u32) {
        let give_amount = give_amount_opt.unwrap_or(1);
        if let Ok(item) = Item::new_from_asset(&item_name.replace(['/', '\\'], ".")) {
            let mut item: Item = item;
            let mut res = Ok(());

            const MAX_GIVE_AMOUNT: u32 = 2000;
            // Cap give_amount for non-stackable items
            let give_amount = if item.is_stackable() {
                give_amount
            } else {
                give_amount.min(MAX_GIVE_AMOUNT)
            };

            if let Ok(()) = item.set_amount(give_amount) {
                server
                    .state
                    .ecs()
                    .write_storage::<Inventory>()
                    .get_mut(target)
                    .map(|mut inv| {
                        // NOTE: Deliberately ignores items that couldn't be pushed.
                        if inv.push(item).is_err() {
                            res = Err(format!(
                                "Player inventory full. Gave 0 of {} items.",
                                give_amount
                            ));
                        }
                    });
            } else {
                let ability_map = server.state.ecs().read_resource::<AbilityMap>();
                let msm = server.state.ecs().read_resource::<MaterialStatManifest>();
                // This item can't stack. Give each item in a loop.
                server
                    .state
                    .ecs()
                    .write_storage::<Inventory>()
                    .get_mut(target)
                    .map(|mut inv| {
                        for i in 0..give_amount {
                            // NOTE: Deliberately ignores items that couldn't be pushed.
                            if inv.push(item.duplicate(&ability_map, &msm)).is_err() {
                                res = Err(format!(
                                    "Player inventory full. Gave {} of {} items.",
                                    i, give_amount
                                ));
                                break;
                            }
                        }
                    });
            }

            insert_or_replace_component(
                server,
                target,
                comp::InventoryUpdate::new(comp::InventoryUpdateEvent::Given),
                "target",
            )?;
            res
        } else {
            Err(format!("Invalid item: {}", item_name))
        }
    } else {
        Err(action.help_string())
    }
}

fn handle_make_block(
    server: &mut Server,
    _client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    if let (Some(block_name), r, g, b) = parse_cmd_args!(args, String, u8, u8, u8) {
        if let Ok(bk) = BlockKind::from_str(block_name.as_str()) {
            let pos = position(server, target, "target")?;
            let new_block = Block::new(bk, Rgb::new(r, g, b).map(|e| e.unwrap_or(255)));
            let pos = pos.0.map(|e| e.floor() as i32);
            server.state.set_block(pos, new_block);
            #[cfg(feature = "persistent_world")]
            if let Some(terrain_persistence) = server
                .state
                .ecs()
                .try_fetch_mut::<crate::TerrainPersistence>()
                .as_mut()
            {
                terrain_persistence.set_block(pos, new_block);
            }
            Ok(())
        } else {
            Err(format!("Invalid block kind: {}", block_name))
        }
    } else {
        Err(action.help_string())
    }
}

fn handle_make_npc(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    let (entity_config, number) = parse_cmd_args!(args, String, i8);

    let entity_config = entity_config.ok_or_else(|| action.help_string())?;
    let number = match number {
        Some(i8::MIN..=0) => {
            return Err("Number of entities should be at least 1".to_owned());
        },
        Some(50..=i8::MAX) => {
            return Err("Number of entities should be less than 50".to_owned());
        },
        Some(number) => number,
        None => 1,
    };

    let config = match EntityConfig::load(&entity_config) {
        Ok(asset) => asset.read(),
        Err(_err) => return Err(format!("Failed to load entity config: {}", entity_config)),
    };

    let mut loadout_rng = thread_rng();
    for _ in 0..number {
        let comp::Pos(pos) = position(server, target, "target")?;
        let entity_info = EntityInfo::at(pos).with_entity_config(
            config.clone(),
            Some(&entity_config),
            &mut loadout_rng,
        );

        match NpcData::from_entity_info(entity_info) {
            NpcData::Waypoint(_) => {
                return Err("Waypoint spawning is not implemented".to_owned());
            },
            NpcData::Data {
                inventory,
                pos,
                stats,
                skill_set,
                poise,
                health,
                body,
                agent,
                alignment,
                scale,
                loot,
            } => {
                let mut entity_builder = server
                    .state
                    .create_npc(pos, stats, skill_set, health, poise, inventory, body)
                    .with(alignment)
                    .with(scale)
                    .with(comp::Vel(Vec3::new(0.0, 0.0, 0.0)));

                if let Some(agent) = agent {
                    entity_builder = entity_builder.with(agent);
                }

                if let Some(drop_item) = loot.to_item() {
                    entity_builder = entity_builder.with(comp::ItemDrop(drop_item));
                }

                // Some would say it's a hack, some would say it's incomplete
                // simulation. But this is what we do to avoid PvP between npc.
                let npc_group = match alignment {
                    Alignment::Enemy => Some(comp::group::ENEMY),
                    Alignment::Npc | Alignment::Tame => Some(comp::group::NPC),
                    Alignment::Wild | Alignment::Passive | Alignment::Owned(_) => None,
                };
                if let Some(group) = npc_group {
                    entity_builder = entity_builder.with(group);
                }
                entity_builder.build();
            },
        };
    }

    server.notify_client(
        client,
        ServerGeneral::server_msg(
            ChatType::CommandInfo,
            format!("Spawned {} entities from config: {}", number, entity_config),
        ),
    );

    Ok(())
}

fn handle_make_sprite(
    server: &mut Server,
    _client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    if let Some(sprite_name) = parse_cmd_args!(args, String) {
        if let Ok(sk) = SpriteKind::try_from(sprite_name.as_str()) {
            let pos = position(server, target, "target")?;
            let pos = pos.0.map(|e| e.floor() as i32);
            let new_block = server
                .state
                .get_block(pos)
                // TODO: Make more principled.
                .unwrap_or_else(|| Block::air(SpriteKind::Empty))
                .with_sprite(sk);
            server.state.set_block(pos, new_block);
            #[cfg(feature = "persistent_world")]
            if let Some(terrain_persistence) = server
                .state
                .ecs()
                .try_fetch_mut::<crate::TerrainPersistence>()
                .as_mut()
            {
                terrain_persistence.set_block(pos, new_block);
            }
            Ok(())
        } else {
            Err(format!("Invalid sprite kind: {}", sprite_name))
        }
    } else {
        Err(action.help_string())
    }
}

fn handle_motd(
    server: &mut Server,
    client: EcsEntity,
    _target: EcsEntity,
    _args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    server.notify_client(
        client,
        ServerGeneral::server_msg(
            ChatType::CommandInfo,
            (*server.editable_settings().server_description).clone(),
        ),
    );
    Ok(())
}

fn handle_set_motd(
    server: &mut Server,
    client: EcsEntity,
    _target: EcsEntity,
    args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    let data_dir = server.data_dir();
    let client_uuid = uuid(server, client, "client")?;
    // Ensure the person setting this has a real role in the settings file, since
    // it's persistent.
    let _client_real_role = real_role(server, client_uuid, "client")?;
    match parse_cmd_args!(args, String) {
        Some(msg) => {
            let edit =
                server
                    .editable_settings_mut()
                    .server_description
                    .edit(data_dir.as_ref(), |d| {
                        let info = format!("Server description set to {:?}", msg);
                        **d = msg;
                        Some(info)
                    });
            drop(data_dir);
            edit_setting_feedback(server, client, edit, || {
                unreachable!("edit always returns Some")
            })
        },
        None => {
            let edit =
                server
                    .editable_settings_mut()
                    .server_description
                    .edit(data_dir.as_ref(), |d| {
                        d.clear();
                        Some("Removed server description".to_string())
                    });
            drop(data_dir);
            edit_setting_feedback(server, client, edit, || {
                unreachable!("edit always returns Some")
            })
        },
    }
}

fn handle_jump(
    server: &mut Server,
    _client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    if let (Some(x), Some(y), Some(z)) = parse_cmd_args!(args, f32, f32, f32) {
        position_mut(server, target, "target", |current_pos| {
            current_pos.0 += Vec3::new(x, y, z)
        })
    } else {
        Err(action.help_string())
    }
}

fn handle_goto(
    server: &mut Server,
    _client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    if let (Some(x), Some(y), Some(z)) = parse_cmd_args!(args, f32, f32, f32) {
        position_mut(server, target, "target", |current_pos| {
            current_pos.0 = Vec3::new(x, y, z)
        })
    } else {
        Err(action.help_string())
    }
}

/// TODO: Add autocompletion if possible (might require modifying enum to handle
/// dynamic values).
fn handle_site(
    server: &mut Server,
    _client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    #[cfg(feature = "worldgen")]
    if let Some(dest_name) = parse_cmd_args!(args, String) {
        let site = server
            .world
            .civs()
            .sites()
            .find(|site| {
                site.site_tmp
                    .map_or(false, |id| server.index.sites[id].name() == dest_name)
            })
            .ok_or_else(|| "Site not found".to_string())?;

        let site_pos = server.world.find_accessible_pos(
            server.index.as_index_ref(),
            TerrainChunkSize::center_wpos(site.center),
            false,
        );

        position_mut(server, target, "target", |current_pos| {
            current_pos.0 = site_pos
        })
    } else {
        Err(action.help_string())
    }

    #[cfg(not(feature = "worldgen"))]
    Ok(())
}

fn handle_home(
    server: &mut Server,
    _client: EcsEntity,
    target: EcsEntity,
    _args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    let home_pos = server.state.mut_resource::<SpawnPoint>().0;
    let time = *server.state.mut_resource::<Time>();

    position_mut(server, target, "target", |current_pos| {
        current_pos.0 = home_pos
    })?;
    insert_or_replace_component(
        server,
        target,
        comp::Waypoint::temp_new(home_pos, time),
        "target",
    )
}

fn handle_kill(
    server: &mut Server,
    _client: EcsEntity,
    target: EcsEntity,
    _args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    server
        .state
        .ecs_mut()
        .write_storage::<comp::Health>()
        .get_mut(target)
        .map(|mut h| h.kill());
    Ok(())
}

fn handle_time(
    server: &mut Server,
    client: EcsEntity,
    _target: EcsEntity,
    args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    const DAY: u64 = 86400;

    let time_in_seconds = server.state.mut_resource::<TimeOfDay>().0;
    let current_day = time_in_seconds as u64 / DAY;
    let day_start = (current_day * DAY) as f64;

    // Find the next occurence of the given time in the day/night cycle
    let next_cycle = |time| {
        let new_time = day_start + time;
        new_time
            + if new_time < time_in_seconds {
                DAY as f64
            } else {
                0.0
            }
    };

    let time = parse_cmd_args!(args, String);
    let new_time = match time.as_deref() {
        Some("midnight") => {
            next_cycle(NaiveTime::from_hms(0, 0, 0).num_seconds_from_midnight() as f64)
        },
        Some("night") => {
            next_cycle(NaiveTime::from_hms(20, 0, 0).num_seconds_from_midnight() as f64)
        },
        Some("dawn") => next_cycle(NaiveTime::from_hms(5, 0, 0).num_seconds_from_midnight() as f64),
        Some("morning") => {
            next_cycle(NaiveTime::from_hms(8, 0, 0).num_seconds_from_midnight() as f64)
        },
        Some("day") => next_cycle(NaiveTime::from_hms(10, 0, 0).num_seconds_from_midnight() as f64),
        Some("noon") => {
            next_cycle(NaiveTime::from_hms(12, 0, 0).num_seconds_from_midnight() as f64)
        },
        Some("dusk") => {
            next_cycle(NaiveTime::from_hms(17, 0, 0).num_seconds_from_midnight() as f64)
        },
        Some(n) => match n.parse::<f64>() {
            Ok(n) => {
                if n < 0.0 {
                    return Err(format!("{} is invalid, cannot be negative.", n));
                }
                // Seconds from next midnight
                next_cycle(0.0) + n
            },
            Err(_) => match NaiveTime::parse_from_str(n, "%H:%M") {
                // Relative to current day
                Ok(time) => next_cycle(time.num_seconds_from_midnight() as f64),
                // Accept `u12345`, seconds since midnight day 0
                Err(_) => match n
                    .get(1..)
                    .filter(|_| n.starts_with('u'))
                    .and_then(|n| n.trim_start_matches('u').parse::<u64>().ok())
                {
                    // Absolute time (i.e. from world epoch)
                    Some(n) => {
                        if (n as f64) < time_in_seconds {
                            return Err(format!(
                                "{} is before the current time, time cannot go backwards.",
                                n
                            ));
                        }
                        n as f64
                    },
                    None => {
                        return Err(format!("{} is not a valid time.", n));
                    },
                },
            },
        },
        None => {
            // Would this ever change? Perhaps in a few hundred thousand years some
            // game archeologists of the future will resurrect the best game of all
            // time which, obviously, would be Veloren. By that time, the inescapable
            // laws of thermodynamics will mean that the earth's rotation period
            // would be slower. Of course, a few hundred thousand years is enough
            // for the circadian rhythm of human biology to have shifted to account
            // accordingly. When booting up Veloren for the first time in 337,241
            // years, they might feel a touch of anguish at the fact that their
            // earth days and the days within the game do not neatly divide into
            // one-another. Understandably, they'll want to change this. Who
            // wouldn't? It would be like turning the TV volume up to an odd number
            // or having a slightly untuned radio (assuming they haven't begun
            // broadcasting information directly into their brains). Totally
            // unacceptable. No, the correct and proper thing to do would be to
            // release a retroactive definitive edition DLC for $99 with the very
            // welcome addition of shorter day periods and a complementary
            // 'developer commentary' mode created by digging up the long-decayed
            // skeletons of the Veloren team, measuring various attributes of their
            // jawlines, and using them to recreate their voices. But how to go about
            // this Herculean task? This code is gibberish! The last of the core Rust
            // dev team died exactly 337,194 years ago! Rust is now a long-forgotten
            // dialect of the ancient ones, lost to the sands of time. Ashes to ashes,
            // dust to dust. When all hope is lost, one particularly intrepid
            // post-human hominid exployed by the 'Veloren Revival Corp' (no doubt we
            // still won't have gotten rid of this blasted 'capitalism' thing by then)
            // might notice, after years of searching, a particularly curious
            // inscription within the code. The letters `D`, `A`, `Y`. Curious! She
            // consults the post-human hominid scholars of the old. Care to empathise
            // with her shock when she discovers that these symbols, as alien as they
            // may seem, correspond exactly to the word `ⓕя𝐢ᵇᵇ𝔩E`, the word for
            // 'day' in the post-human hominid language, which is of course universal.
            // Imagine also her surprise when, after much further translating, she
            // finds a comment predicting her very existence and her struggle to
            // decode this great mystery. Rejoice! The Veloren Revival Corp. may now
            // persist with their great Ultimate Edition DLC because the day period
            // might now be changed because they have found the constant that controls
            // it! Everybody was henceforth happy until the end of time.
            //
            // This one's for you, xMac ;)
            let current_time = NaiveTime::from_num_seconds_from_midnight_opt(
                // Wraps around back to 0s if it exceeds 24 hours (24 hours = 86400s)
                (time_in_seconds as u64 % DAY) as u32,
                0,
            );
            let msg = match current_time {
                Some(time) => format!("It is {}", time.format("%H:%M")),
                None => String::from("Unknown Time"),
            };
            server.notify_client(
                client,
                ServerGeneral::server_msg(ChatType::CommandInfo, msg),
            );
            return Ok(());
        },
    };

    server.state.mut_resource::<TimeOfDay>().0 = new_time;

    // Update all clients with the new TimeOfDay (without this they would have to
    // wait for the next 100th tick to receive the update).
    let mut tod_lazymsg = None;
    let clients = server.state.ecs().read_storage::<Client>();
    let calendar = server.state.ecs().read_resource::<Calendar>();
    for client in (&clients).join() {
        let msg = tod_lazymsg.unwrap_or_else(|| {
            client.prepare(ServerGeneral::TimeOfDay(
                TimeOfDay(new_time),
                (*calendar).clone(),
            ))
        });
        let _ = client.send_prepared(&msg);
        tod_lazymsg = Some(msg);
    }

    if let Some(new_time) =
        NaiveTime::from_num_seconds_from_midnight_opt(((new_time as u64) % 86400) as u32, 0)
    {
        server.notify_client(
            client,
            ServerGeneral::server_msg(
                ChatType::CommandInfo,
                format!("Time changed to: {}", new_time.format("%H:%M")),
            ),
        );
    }
    Ok(())
}

fn handle_health(
    server: &mut Server,
    _client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    if let Some(hp) = parse_cmd_args!(args, f32) {
        if let Some(mut health) = server
            .state
            .ecs()
            .write_storage::<comp::Health>()
            .get_mut(target)
        {
            let time = server.state.ecs().read_resource::<Time>();
            let change = comp::HealthChange {
                amount: hp - health.current(),
                by: None,
                cause: None,
                crit: false,
                time: *time,
                instance: rand::random(),
            };
            health.change_by(change);
            Ok(())
        } else {
            Err("You have no health".into())
        }
    } else {
        Err("You must specify health amount!".into())
    }
}

fn handle_alias(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    if let Some(alias) = parse_cmd_args!(args, String) {
        // Prevent silly aliases
        comp::Player::alias_validate(&alias).map_err(|e| e.to_string())?;

        let old_alias_optional = server
            .state
            .ecs_mut()
            .write_storage::<comp::Player>()
            .get_mut(target)
            .map(|mut player| std::mem::replace(&mut player.alias, alias));

        // Update name on client player lists
        let ecs = server.state.ecs();
        if let (Some(uid), Some(player), Some(old_alias)) = (
            ecs.read_storage::<Uid>().get(target),
            ecs.read_storage::<comp::Player>().get(target),
            old_alias_optional,
        ) {
            let msg = ServerGeneral::PlayerListUpdate(PlayerListUpdate::Alias(
                *uid,
                player.alias.clone(),
            ));
            server.state.notify_players(msg);

            // Announce alias change if target has a Body.
            if ecs.read_storage::<comp::Body>().get(target).is_some() {
                server.state.notify_players(ServerGeneral::server_msg(
                    ChatType::CommandInfo,
                    format!("{} is now known as {}.", old_alias, player.alias),
                ));
            }
        }
        if client != target {
            // Notify target that an admin changed the alias due to /sudo
            server.notify_client(
                target,
                ServerGeneral::server_msg(ChatType::CommandInfo, "An admin changed your alias."),
            );
        }
        Ok(())
    } else {
        Err(action.help_string())
    }
}

fn handle_tp(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    let player = if let Some(alias) = parse_cmd_args!(args, String) {
        find_alias(server.state.ecs(), &alias)?.0
    } else if client != target {
        client
    } else {
        return Err(action.help_string());
    };
    let player_pos = position(server, player, "player")?;
    position_mut(server, target, "target", |target_pos| {
        *target_pos = player_pos
    })
}

fn handle_spawn(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    match parse_cmd_args!(args, String, npc::NpcBody, u32, bool) {
        (Some(opt_align), Some(npc::NpcBody(id, mut body)), opt_amount, opt_ai) => {
            let uid = uid(server, target, "target")?;
            let alignment = parse_alignment(uid, &opt_align)?;
            let amount = opt_amount.filter(|x| *x > 0).unwrap_or(1).min(50);

            let ai = opt_ai.unwrap_or(true);
            let pos = position(server, target, "target")?;
            let mut agent = comp::Agent::from_body(&body());

            // If unowned, the agent should stay in a particular place
            if !matches!(alignment, comp::Alignment::Owned(_)) {
                agent = agent.with_patrol_origin(pos.0);
            }

            for _ in 0..amount {
                let vel = Vec3::new(
                    thread_rng().gen_range(-2.0..3.0),
                    thread_rng().gen_range(-2.0..3.0),
                    10.0,
                );

                let body = body();
                let loadout = LoadoutBuilder::from_default(&body).build();
                let inventory = Inventory::with_loadout(loadout, body);

                let mut entity_base = server
                    .state
                    .create_npc(
                        pos,
                        comp::Stats::new(get_npc_name(id, npc::BodyType::from_body(body))),
                        comp::SkillSet::default(),
                        Some(comp::Health::new(body, 1)),
                        comp::Poise::new(body),
                        inventory,
                        body,
                    )
                    .with(comp::Vel(vel))
                    .with(body.scale())
                    .with(alignment);

                if ai {
                    entity_base = entity_base.with(agent.clone());
                }

                let new_entity = entity_base.build();

                // Add to group system if a pet
                if matches!(alignment, comp::Alignment::Owned { .. }) {
                    let server_eventbus =
                        server.state.ecs().read_resource::<EventBus<ServerEvent>>();
                    server_eventbus.emit_now(ServerEvent::TamePet {
                        owner_entity: target,
                        pet_entity: new_entity,
                    });
                } else if let Some(group) = match alignment {
                    Alignment::Wild => None,
                    Alignment::Passive => None,
                    Alignment::Enemy => Some(comp::group::ENEMY),
                    Alignment::Npc | Alignment::Tame => Some(comp::group::NPC),
                    comp::Alignment::Owned(_) => unreachable!(),
                } {
                    insert_or_replace_component(server, new_entity, group, "new entity")?;
                }

                if let Some(uid) = server.state.ecs().uid_from_entity(new_entity) {
                    server.notify_client(
                        client,
                        ServerGeneral::server_msg(
                            ChatType::CommandInfo,
                            format!("Spawned entity with ID: {}", uid),
                        ),
                    );
                }
            }
            server.notify_client(
                client,
                ServerGeneral::server_msg(
                    ChatType::CommandInfo,
                    format!("Spawned {} entities", amount),
                ),
            );
            Ok(())
        },
        _ => Err(action.help_string()),
    }
}

fn handle_spawn_training_dummy(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    _args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    let pos = position(server, target, "target")?;
    let vel = Vec3::new(
        thread_rng().gen_range(-2.0..3.0),
        thread_rng().gen_range(-2.0..3.0),
        10.0,
    );

    let body = comp::Body::Object(comp::object::Body::TrainingDummy);

    let stats = comp::Stats::new("Training Dummy".to_string());
    let skill_set = comp::SkillSet::default();
    let health = comp::Health::new(body, 0);
    let poise = comp::Poise::new(body);

    server
        .state
        .create_npc(
            pos,
            stats,
            skill_set,
            Some(health),
            poise,
            Inventory::with_empty(),
            body,
        )
        .with(comp::Vel(vel))
        .build();

    server.notify_client(
        client,
        ServerGeneral::server_msg(ChatType::CommandInfo, "Spawned a training dummy"),
    );
    Ok(())
}

fn handle_spawn_airship(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    let angle = parse_cmd_args!(args, f32);
    let mut pos = position(server, target, "target")?;
    pos.0.z += 50.0;
    const DESTINATION_RADIUS: f32 = 2000.0;
    let angle = angle.map(|a| a * std::f32::consts::PI / 180.0);
    let destination = angle.map(|a| {
        pos.0
            + Vec3::new(
                DESTINATION_RADIUS * a.cos(),
                DESTINATION_RADIUS * a.sin(),
                200.0,
            )
    });
    let mut rng = thread_rng();
    let ship = comp::ship::Body::random_airship_with(&mut rng);
    let mut builder = server
        .state
        .create_ship(pos, ship, |ship| ship.make_collider(), true)
        .with(LightEmitter {
            col: Rgb::new(1.0, 0.65, 0.2),
            strength: 2.0,
            flicker: 1.0,
            animated: true,
        });
    if let Some(pos) = destination {
        let (kp, ki, kd) = comp::agent::pid_coefficients(&comp::Body::Ship(ship));
        fn pure_z(sp: Vec3<f32>, pv: Vec3<f32>) -> f32 { (sp - pv).z }
        let agent = comp::Agent::from_body(&comp::Body::Ship(ship))
            .with_destination(pos)
            .with_position_pid_controller(comp::PidController::new(kp, ki, kd, pos, 0.0, pure_z));
        builder = builder.with(agent);
    }
    builder.build();

    server.notify_client(
        client,
        ServerGeneral::server_msg(ChatType::CommandInfo, "Spawned an airship"),
    );
    Ok(())
}

fn handle_spawn_ship(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    let angle = parse_cmd_args!(args, f32);
    let mut pos = position(server, target, "target")?;
    pos.0.z += 50.0;
    const DESTINATION_RADIUS: f32 = 2000.0;
    let angle = angle.map(|a| a * std::f32::consts::PI / 180.0);
    let destination = angle.map(|a| {
        pos.0
            + Vec3::new(
                DESTINATION_RADIUS * a.cos(),
                DESTINATION_RADIUS * a.sin(),
                200.0,
            )
    });
    let mut rng = thread_rng();
    let ship = comp::ship::Body::random_ship_with(&mut rng);
    let mut builder = server
        .state
        .create_ship(pos, ship, |ship| ship.make_collider(), true)
        .with(LightEmitter {
            col: Rgb::new(1.0, 0.65, 0.2),
            strength: 2.0,
            flicker: 1.0,
            animated: true,
        });
    if let Some(pos) = destination {
        let (kp, ki, kd) = comp::agent::pid_coefficients(&comp::Body::Ship(ship));
        fn pure_z(sp: Vec3<f32>, pv: Vec3<f32>) -> f32 { (sp - pv).z }
        let agent = comp::Agent::from_body(&comp::Body::Ship(ship))
            .with_destination(pos)
            .with_position_pid_controller(comp::PidController::new(kp, ki, kd, pos, 0.0, pure_z));
        builder = builder.with(agent);
    }
    builder.build();

    server.notify_client(
        client,
        ServerGeneral::server_msg(ChatType::CommandInfo, "Spawned a ship"),
    );
    Ok(())
}

fn handle_make_volume(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    _args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    use comp::body::ship::figuredata::VoxelCollider;

    //let () = parse_args!(args);
    let pos = position(server, target, "target")?;
    let ship = comp::ship::Body::Volume;
    let sz = Vec3::new(15, 15, 15);
    let collider = {
        let terrain = server.state().terrain();
        comp::Collider::Volume(Arc::new(VoxelCollider::from_fn(sz, |rpos| {
            terrain
                .get(pos.0.map(|e| e.floor() as i32) + rpos - sz.map(|e| e as i32) / 2)
                .ok()
                .copied()
                .unwrap_or_else(Block::empty)
        })))
    };
    server
        .state
        .create_ship(
            comp::Pos(pos.0 + Vec3::unit_z() * 50.0),
            ship,
            move |_| collider,
            true,
        )
        .build();

    server.notify_client(
        client,
        ServerGeneral::server_msg(ChatType::CommandInfo, "Created a volume"),
    );
    Ok(())
}

fn handle_spawn_campfire(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    _args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    let pos = position(server, target, "target")?;
    server
        .state
        .create_object(pos, comp::object::Body::CampfireLit)
        .with(LightEmitter {
            col: Rgb::new(1.0, 0.65, 0.2),
            strength: 2.0,
            flicker: 1.0,
            animated: true,
        })
        .with(WaypointArea::default())
        .with(comp::Auras::new(vec![
            Aura::new(
                AuraKind::Buff {
                    kind: BuffKind::CampfireHeal,
                    data: BuffData::new(0.02, Some(Duration::from_secs(1))),
                    category: BuffCategory::Natural,
                    source: BuffSource::World,
                },
                5.0,
                None,
                AuraTarget::All,
            ),
            Aura::new(
                AuraKind::Buff {
                    kind: BuffKind::Burning,
                    data: BuffData::new(2.0, Some(Duration::from_secs(10))),
                    category: BuffCategory::Natural,
                    source: BuffSource::World,
                },
                0.7,
                None,
                AuraTarget::All,
            ),
        ]))
        .build();

    server.notify_client(
        client,
        ServerGeneral::server_msg(ChatType::CommandInfo, "Spawned a campfire"),
    );
    Ok(())
}

fn handle_safezone(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    let range = parse_cmd_args!(args, f32);
    let pos = position(server, target, "target")?;
    server.state.create_safezone(range, pos).build();

    server.notify_client(
        client,
        ServerGeneral::server_msg(ChatType::CommandInfo, "Spawned a safe zone"),
    );
    Ok(())
}

fn handle_permit_build(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    if let Some(area_name) = parse_cmd_args!(args, String) {
        let bb_id = area(server, &area_name)?;
        let mut can_build = server.state.ecs().write_storage::<comp::CanBuild>();
        let entry = can_build
            .entry(target)
            .map_err(|_| "Cannot find target entity!".to_string())?;
        let mut comp_can_build = entry.or_insert(comp::CanBuild {
            enabled: false,
            build_areas: HashSet::new(),
        });
        comp_can_build.build_areas.insert(bb_id);
        drop(can_build);
        if client != target {
            server.notify_client(
                target,
                ServerGeneral::server_msg(
                    ChatType::CommandInfo,
                    format!("You are now permitted to build in {}", area_name),
                ),
            );
        }
        server.notify_client(
            client,
            ServerGeneral::server_msg(
                ChatType::CommandInfo,
                format!("Permission to build in {} granted", area_name),
            ),
        );
        Ok(())
    } else {
        Err(action.help_string())
    }
}

fn handle_revoke_build(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    if let Some(area_name) = parse_cmd_args!(args, String) {
        let bb_id = area(server, &area_name)?;
        let mut can_build = server.state.ecs_mut().write_storage::<comp::CanBuild>();
        if let Some(mut comp_can_build) = can_build.get_mut(target) {
            comp_can_build.build_areas.retain(|&x| x != bb_id);
            drop(can_build);
            if client != target {
                server.notify_client(
                    target,
                    ServerGeneral::server_msg(
                        ChatType::CommandInfo,
                        format!("Your permission to build in {} has been revoked", area_name),
                    ),
                );
            }
            server.notify_client(
                client,
                ServerGeneral::server_msg(
                    ChatType::CommandInfo,
                    format!("Permission to build in {} revoked", area_name),
                ),
            );
            Ok(())
        } else {
            Err("You do not have permission to build.".into())
        }
    } else {
        Err(action.help_string())
    }
}

fn handle_revoke_build_all(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    _args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    let ecs = server.state.ecs();

    ecs.write_storage::<comp::CanBuild>().remove(target);
    if client != target {
        server.notify_client(
            target,
            ServerGeneral::server_msg(
                ChatType::CommandInfo,
                "Your build permissions have been revoked.",
            ),
        );
    }
    server.notify_client(
        client,
        ServerGeneral::server_msg(ChatType::CommandInfo, "All build permissions revoked"),
    );
    Ok(())
}

fn handle_players(
    server: &mut Server,
    client: EcsEntity,
    _target: EcsEntity,
    _args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    let ecs = server.state.ecs();

    let entity_tuples = (
        &ecs.entities(),
        &ecs.read_storage::<comp::Player>(),
        &ecs.read_storage::<comp::Stats>(),
    );

    server.notify_client(
        client,
        ServerGeneral::server_msg(
            ChatType::CommandInfo,
            entity_tuples.join().fold(
                format!("{} online players:", entity_tuples.join().count()),
                |s, (_, player, stat)| format!("{}\n[{}]{}", s, player.alias, stat.name,),
            ),
        ),
    );
    Ok(())
}

fn handle_build(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    _args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    if let Some(mut can_build) = server
        .state
        .ecs()
        .write_storage::<comp::CanBuild>()
        .get_mut(target)
    {
        can_build.enabled ^= true;

        let toggle_string = if can_build.enabled { "on" } else { "off" };
        let msg = format!(
            "Toggled build mode {}.{}",
            toggle_string,
            if !can_build.enabled {
                ""
            } else if server.settings().experimental_terrain_persistence {
                " Experimental terrain persistence is enabled. The server will attempt to persist \
                 changes, but this is not guaranteed."
            } else {
                " Changes will not be persisted when a chunk unloads."
            },
        );

        let chat_msg = ServerGeneral::server_msg(ChatType::CommandInfo, msg);
        if client != target {
            server.notify_client(target, chat_msg.clone());
        }
        server.notify_client(client, chat_msg);
        Ok(())
    } else {
        Err("You do not have permission to build.".into())
    }
}

fn handle_build_area_add(
    server: &mut Server,
    client: EcsEntity,
    _target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    if let (Some(area_name), Some(xlo), Some(xhi), Some(ylo), Some(yhi), Some(zlo), Some(zhi)) =
        parse_cmd_args!(args, String, i32, i32, i32, i32, i32, i32)
    {
        let build_areas = server.state.mut_resource::<BuildAreas>();
        let msg = ServerGeneral::server_msg(
            ChatType::CommandInfo,
            format!("Created build zone {}", area_name),
        );
        build_areas
            .insert(area_name, Aabb {
                min: Vec3::new(xlo, ylo, zlo),
                max: Vec3::new(xhi, yhi, zhi),
            })
            .map_err(|area_name| format!("Build zone {} already exists!", area_name))?;
        server.notify_client(client, msg);
        Ok(())
    } else {
        Err(action.help_string())
    }
}

fn handle_build_area_list(
    server: &mut Server,
    client: EcsEntity,
    _target: EcsEntity,
    _args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    let build_areas = server.state.mut_resource::<BuildAreas>();
    let msg = ServerGeneral::server_msg(
        ChatType::CommandInfo,
        build_areas.area_names().iter().fold(
            "Build Areas:".to_string(),
            |acc, (area_name, bb_id)| {
                if let Some(aabb) = build_areas.areas().get(*bb_id) {
                    format!("{}\n{}: {} to {}", acc, area_name, aabb.min, aabb.max)
                } else {
                    acc
                }
            },
        ),
    );

    server.notify_client(client, msg);
    Ok(())
}

fn handle_build_area_remove(
    server: &mut Server,
    client: EcsEntity,
    _target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    if let Some(area_name) = parse_cmd_args!(args, String) {
        let build_areas = server.state.mut_resource::<BuildAreas>();

        build_areas.remove(&area_name).map_err(|err| match err {
            BuildAreaError::Reserved => format!(
                "Build area is reserved and cannot be removed: {}",
                area_name
            ),
            BuildAreaError::NotFound => format!("No such build area {}", area_name),
        })?;
        server.notify_client(
            client,
            ServerGeneral::server_msg(
                ChatType::CommandInfo,
                format!("Removed build zone {}", area_name),
            ),
        );
        Ok(())
    } else {
        Err(action.help_string())
    }
}

fn handle_help(
    server: &mut Server,
    client: EcsEntity,
    _target: EcsEntity,
    args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    if let Some(cmd) = parse_cmd_args!(args, ServerChatCommand) {
        server.notify_client(
            client,
            ServerGeneral::server_msg(ChatType::CommandInfo, cmd.help_string()),
        )
    } else {
        let mut message = String::new();
        let entity_role = server.entity_admin_role(client);

        // Iterate through all commands you have permission to use.
        ServerChatCommand::iter()
            .filter(|cmd| cmd.needs_role() <= entity_role)
            .for_each(|cmd| {
                message += &cmd.help_string();
                message += "\n";
            });
        message += "Additionally, you can use the following shortcuts:";
        ServerChatCommand::iter()
            .filter_map(|cmd| cmd.short_keyword().map(|k| (k, cmd)))
            .for_each(|(k, cmd)| {
                message += &format!(" /{} => /{}", k, cmd.keyword());
            });

        server.notify_client(
            client,
            ServerGeneral::server_msg(ChatType::CommandInfo, message),
        )
    }
    Ok(())
}

fn parse_alignment(owner: Uid, alignment: &str) -> CmdResult<Alignment> {
    match alignment {
        "wild" => Ok(Alignment::Wild),
        "enemy" => Ok(Alignment::Enemy),
        "npc" => Ok(Alignment::Npc),
        "pet" => Ok(comp::Alignment::Owned(owner)),
        _ => Err(format!("Invalid alignment: {:?}", alignment)),
    }
}

fn handle_kill_npcs(
    server: &mut Server,
    client: EcsEntity,
    _target: EcsEntity,
    args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    let kill_pets = if let Some(kill_option) = parse_cmd_args!(args, String) {
        kill_option.contains("--also-pets")
    } else {
        false
    };

    let to_kill = {
        let ecs = server.state.ecs();
        let entities = ecs.entities();
        let healths = ecs.write_storage::<comp::Health>();
        let players = ecs.read_storage::<comp::Player>();
        let alignments = ecs.read_storage::<Alignment>();

        (&entities, &healths, !&players, alignments.maybe())
            .join()
            .filter_map(|(entity, _health, (), alignment)| {
                let should_kill = kill_pets
                    || if let Some(Alignment::Owned(owned)) = alignment {
                        ecs.entity_from_uid(owned.0)
                            .map_or(true, |owner| !players.contains(owner))
                    } else {
                        true
                    };

                should_kill.then_some(entity)
            })
            .collect::<Vec<_>>()
    };
    let count = to_kill.len();
    for entity in to_kill {
        // Directly remove entities instead of modifying health to avoid loot drops.
        if let Err(e) = server.state.delete_entity_recorded(entity) {
            error!(?e, ?entity, "Failed to delete entity");
        }
    }
    let text = if count > 0 {
        format!("Destroyed {} NPCs.", count)
    } else {
        "No NPCs on server.".to_string()
    };

    server.notify_client(
        client,
        ServerGeneral::server_msg(ChatType::CommandInfo, text),
    );

    Ok(())
}

fn handle_kit(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    use common::cmd::KitManifest;

    let notify = |server: &mut Server, kit_name: &str| {
        server.notify_client(
            client,
            ServerGeneral::server_msg(ChatType::CommandInfo, format!("Gave kit: {}", kit_name)),
        );
    };
    let name = parse_cmd_args!(args, String).ok_or_else(|| action.help_string())?;

    match name.as_str() {
        "all" => {
            // TODO: we will probably want to handle modular items here too
            let items = &ITEM_SPECS;
            let res = push_kit(
                items
                    .iter()
                    .map(|item_id| (KitSpec::Item(item_id.to_string()), 1)),
                items.len(),
                server,
                target,
            );
            if res.is_ok() {
                notify(server, "all");
            }
            res
        },
        kit_name => {
            let kits = KitManifest::load(KIT_MANIFEST_PATH)
                .map(|kits| kits.read())
                .map_err(|_| format!("Could not load manifest file {}", KIT_MANIFEST_PATH))?;

            let kit = kits
                .0
                .get(kit_name)
                .ok_or(format!("Kit '{}' not found", kit_name))?;

            let res = push_kit(
                kit.iter()
                    .map(|(item_id, quantity)| (item_id.clone(), *quantity)),
                kit.len(),
                server,
                target,
            );
            if res.is_ok() {
                notify(server, kit_name);
            }
            res
        },
    }
}

fn push_kit<I>(kit: I, count: usize, server: &mut Server, target: EcsEntity) -> CmdResult<()>
where
    I: Iterator<Item = (KitSpec, u32)>,
{
    if let (Some(mut target_inventory), mut target_inv_update) = (
        server
            .state()
            .ecs()
            .write_storage::<Inventory>()
            .get_mut(target),
        server.state.ecs().write_storage::<comp::InventoryUpdate>(),
    ) {
        // TODO: implement atomic `insert_all_or_nothing` on Inventory
        if target_inventory.free_slots() < count {
            return Err("Inventory doesn't have enough slots".to_owned());
        }

        for (item_id, quantity) in kit {
            push_item(item_id, quantity, server, &mut |item| {
                let res = target_inventory.push(item);
                let _ = target_inv_update.insert(
                    target,
                    comp::InventoryUpdate::new(comp::InventoryUpdateEvent::Debug),
                );

                res
            })?;
        }

        Ok(())
    } else {
        Err("Could not get inventory".to_string())
    }
}

fn push_item(
    item_id: KitSpec,
    quantity: u32,
    server: &Server,
    push: &mut dyn FnMut(Item) -> Result<(), Item>,
) -> CmdResult<()> {
    let items = match &item_id {
        KitSpec::Item(item_id) => vec![
            Item::new_from_asset(item_id).map_err(|_| format!("Unknown item: {:#?}", item_id))?,
        ],
        KitSpec::ModularWeapon { tool, material } => {
            comp::item::modular::generate_weapons(*tool, *material, None)
                .map_err(|err| format!("{:#?}", err))?
        },
    };

    let mut res = Ok(());
    for mut item in items {
        // Either push stack or push one by one.
        if item.is_stackable() {
            // FIXME: in theory, this can fail,
            // but we don't have stack sizes yet.
            let _ = item.set_amount(quantity);
            res = push(item);
        } else {
            let ability_map = server.state.ecs().read_resource::<AbilityMap>();
            let msm = server.state.ecs().read_resource::<MaterialStatManifest>();

            for _ in 0..quantity {
                res = push(item.duplicate(&ability_map, &msm));

                if res.is_err() {
                    break;
                }
            }
        }

        // I think it's possible to pick-up item during this loop
        // and fail into case where you had space but now you don't?
        if res.is_err() {
            return Err("Can't fit item to inventory".to_owned());
        }
    }

    Ok(())
}

fn handle_object(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    let obj_type = parse_cmd_args!(args, String);

    let pos = position(server, target, "target")?;
    let ori = server
        .state
        .ecs()
        .read_storage::<comp::Ori>()
        .get(target)
        .copied()
        .ok_or_else(|| "Cannot get orientation for target".to_string())?;
    /*let builder = server.state
    .create_object(pos, ori, obj_type)
    .with(ori);*/
    let obj_str_res = obj_type.as_deref();
    if let Some(obj_type) = comp::object::ALL_OBJECTS
        .iter()
        .find(|o| Some(o.to_string()) == obj_str_res)
    {
        server
            .state
            .create_object(pos, *obj_type)
            .with(
                comp::Ori::from_unnormalized_vec(
                    // converts player orientation into a 90° rotation for the object by using
                    // the axis with the highest value
                    {
                        let look_dir = ori.look_dir();
                        look_dir.map(|e| {
                            if e.abs() == look_dir.map(|e| e.abs()).reduce_partial_max() {
                                e
                            } else {
                                0.0
                            }
                        })
                    },
                )
                .unwrap_or_default(),
            )
            .build();
        server.notify_client(
            client,
            ServerGeneral::server_msg(
                ChatType::CommandInfo,
                format!("Spawned: {}", obj_str_res.unwrap_or("<Unknown object>")),
            ),
        );
        Ok(())
    } else {
        Err("Object not found!".into())
    }
}

fn handle_light(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    let (opt_r, opt_g, opt_b, opt_x, opt_y, opt_z, opt_s) =
        parse_cmd_args!(args, f32, f32, f32, f32, f32, f32, f32);

    let mut light_emitter = LightEmitter::default();
    let mut light_offset_opt = None;

    if let (Some(r), Some(g), Some(b)) = (opt_r, opt_g, opt_b) {
        if r < 0.0 || g < 0.0 || b < 0.0 {
            return Err("cr, cg and cb values mustn't be negative.".into());
        }

        let r = r.clamp(0.0, 1.0);
        let g = g.clamp(0.0, 1.0);
        let b = b.clamp(0.0, 1.0);
        light_emitter.col = Rgb::new(r, g, b)
    };
    if let (Some(x), Some(y), Some(z)) = (opt_x, opt_y, opt_z) {
        light_offset_opt = Some(comp::LightAnimation {
            offset: Vec3::new(x, y, z),
            col: light_emitter.col,
            strength: 0.0,
        })
    };
    if let Some(s) = opt_s {
        light_emitter.strength = s.max(0.0)
    };
    let pos = position(server, target, "target")?;
    let builder = server
        .state
        .ecs_mut()
        .create_entity_synced()
        .with(pos)
        .with(comp::ForceUpdate::forced())
        .with(light_emitter);
    if let Some(light_offset) = light_offset_opt {
        builder.with(light_offset).build();
    } else {
        builder.build();
    }
    server.notify_client(
        client,
        ServerGeneral::server_msg(ChatType::CommandInfo, "Spawned object."),
    );
    Ok(())
}

fn handle_lantern(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    if let (Some(s), r, g, b) = parse_cmd_args!(args, f32, f32, f32, f32) {
        if let Some(mut light) = server
            .state
            .ecs()
            .write_storage::<LightEmitter>()
            .get_mut(target)
        {
            light.strength = s.clamp(0.1, 10.0);
            if let (Some(r), Some(g), Some(b)) = (r, g, b) {
                light.col = (r.clamp(0.0, 1.0), g.clamp(0.0, 1.0), b.clamp(0.0, 1.0)).into();
                server.notify_client(
                    client,
                    ServerGeneral::server_msg(
                        ChatType::CommandInfo,
                        "You adjusted flame strength and color.",
                    ),
                )
            } else {
                server.notify_client(
                    client,
                    ServerGeneral::server_msg(
                        ChatType::CommandInfo,
                        "You adjusted flame strength.",
                    ),
                )
            }
            Ok(())
        } else {
            Err("Please equip a lantern first".into())
        }
    } else {
        Err(action.help_string())
    }
}

fn handle_explosion(
    server: &mut Server,
    _client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    let power = parse_cmd_args!(args, f32).unwrap_or(8.0);

    const MIN_POWER: f32 = 0.0;
    const MAX_POWER: f32 = 512.0;

    if power > MAX_POWER {
        return Err(format!(
            "Explosion power mustn't be more than {:?}.",
            MAX_POWER
        ));
    } else if power <= 0.0 {
        return Err(format!(
            "Explosion power must be more than {:?}.",
            MIN_POWER
        ));
    }

    let pos = position(server, target, "target")?;
    let owner = server
        .state
        .ecs()
        .read_storage::<Uid>()
        .get(target)
        .copied();
    server
        .state
        .mut_resource::<EventBus<ServerEvent>>()
        .emit_now(ServerEvent::Explosion {
            pos: pos.0,
            explosion: Explosion {
                effects: vec![
                    RadiusEffect::Entity(Effect::Damage(Damage {
                        source: DamageSource::Explosion,
                        kind: DamageKind::Energy,
                        value: 100.0 * power,
                    })),
                    RadiusEffect::TerrainDestruction(power),
                ],
                radius: 3.0 * power,
                reagent: None,
                min_falloff: 0.0,
            },
            owner,
        });
    Ok(())
}

fn handle_waypoint(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    _args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    let pos = position(server, target, "target")?;
    let time = *server.state.mut_resource::<Time>();
    insert_or_replace_component(
        server,
        target,
        comp::Waypoint::temp_new(pos.0, time),
        "target",
    )?;
    server.notify_client(
        client,
        ServerGeneral::server_msg(ChatType::CommandInfo, "Waypoint saved!"),
    );
    server.notify_client(
        target,
        ServerGeneral::Notification(Notification::WaypointSaved),
    );
    Ok(())
}

fn handle_spawn_wiring(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    _args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    let mut pos = position(server, target, "target")?;
    pos.0.x += 3.0;

    let mut outputs1 = HashMap::new();
    outputs1.insert("button".to_string(), OutputFormula::OnCollide {
        value: 1.0,
    });

    // Create the first element of the circuit.
    // This is a coin body. This element does not have any inputs or actions.
    // Instead there is one output. When there is a collision with this element the
    // value of 1.0 will be sent as an input with the "button" label. Any
    // element with an `Input` for the name "button" can use this value as an
    // input. The threshold does not matter as there are no effects for this
    // element.
    let builder1 = server
        .state
        .create_wiring(pos, comp::object::Body::Coins, WiringElement {
            inputs: HashMap::new(),
            outputs: outputs1,
            actions: Vec::new(),
        })
        .with(comp::Density(100_f32));
    let ent1 = builder1.build();

    pos.0.x += 3.0;
    // The second element has no elements in the `inputs` field to start with. When
    // the circuit runs, the input as specified by the `Input` OutputFormula is
    // added to the inputs. The next tick the effect(s) are applied based on the
    // input value.
    let builder2 = server
        .state
        .create_wiring(pos, comp::object::Body::Coins, WiringElement {
            inputs: HashMap::new(),
            outputs: HashMap::new(),
            actions: vec![WiringAction {
                formula: OutputFormula::Input {
                    name: String::from("button"),
                },
                threshold: 0.0,
                effects: vec![WiringActionEffect::SetLight {
                    r: OutputFormula::Input {
                        name: String::from("button"),
                    },
                    g: OutputFormula::Input {
                        name: String::from("button"),
                    },
                    b: OutputFormula::Input {
                        name: String::from("button"),
                    },
                }],
            }],
        })
        .with(comp::Density(100_f32));
    let ent2 = builder2.build();

    pos.0.x += 3.0;
    let builder3 = server
        .state
        .create_wiring(pos, comp::object::Body::TrainingDummy, WiringElement {
            inputs: HashMap::new(),
            outputs: HashMap::new(),
            actions: Vec::new(),
        })
        .with(comp::Density(comp::object::Body::TrainingDummy.density().0))
        .with(Circuit::new(vec![Wire {
            input: WireNode::new(ent1, "button".to_string()),
            output: WireNode::new(ent2, "button".to_string()),
        }]));
    builder3.build();

    server.notify_client(
        client,
        ServerGeneral::server_msg(ChatType::CommandInfo, "Wire"),
    );
    Ok(())
}

fn handle_adminify(
    server: &mut Server,
    client: EcsEntity,
    _target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    if let (Some(alias), desired_role) = parse_cmd_args!(args, String, String) {
        let desired_role = if let Some(mut desired_role) = desired_role {
            desired_role.make_ascii_lowercase();
            Some(match &*desired_role {
                "admin" => AdminRole::Admin,
                "moderator" => AdminRole::Moderator,
                _ => {
                    return Err(action.help_string());
                },
            })
        } else {
            None
        };
        let (player, player_uuid) = find_alias(server.state.ecs(), &alias)?;
        let client_uuid = uuid(server, client, "client")?;
        let uid = uid(server, player, "player")?;

        // Your permanent role, not your temporary role, is what's used to determine
        // what temporary roles you can grant.
        let client_real_role = real_role(server, client_uuid, "client")?;

        // This appears to prevent de-mod / de-admin for mods / admins with access to
        // this command, but it does not in the case where the target is
        // temporary, because `verify_above_role` always values permanent roles
        // above temporary ones.
        verify_above_role(
            server,
            (client, client_uuid),
            (player, player_uuid),
            "Cannot reassign a role for anyone with your role or higher.",
        )?;

        // Ensure that it's not possible to assign someone a higher role than your own
        // (i.e. even if mods had the ability to create temporary mods, they
        // wouldn't be able to create temporary admins).
        //
        // Also note that we perform no more permissions checks after this point based
        // on the assignee's temporary role--even if the player's temporary role
        // is higher than the client's, we still allow the role to be reduced to
        // the selected role, as long as they would have permission to assign it
        // in the first place.  This is consistent with our
        // policy on bans--banning or lengthening a ban (decreasing player permissions)
        // can be done even after an unban or ban shortening (increasing player
        // permissions) by someone with a higher role than the person doing the
        // ban.  So if we change how bans work, we should change how things work
        // here, too, for consistency.
        if desired_role > Some(client_real_role) {
            return Err(
                "Cannot assign someone a temporary role higher than your own permanent one".into(),
            );
        }

        let mut admin_storage = server.state.ecs().write_storage::<comp::Admin>();
        let entry = admin_storage
            .entry(player)
            .map_err(|_| "Cannot find player entity!".to_string())?;
        match (entry, desired_role) {
            (StorageEntry::Vacant(_), None) => {
                return Err("Player already has no role!".into());
            },
            (StorageEntry::Occupied(o), None) => {
                let old_role = o.remove().0;
                server.notify_client(
                    client,
                    ServerGeneral::server_msg(
                        ChatType::CommandInfo,
                        format!("Role removed from player {}: {:?}", alias, old_role),
                    ),
                );
            },
            (entry, Some(desired_role)) => {
                let verb = match entry
                    .replace(comp::Admin(desired_role))
                    .map(|old_admin| old_admin.0.cmp(&desired_role))
                {
                    Some(Ordering::Equal) => {
                        return Err("Player already has that role!".into());
                    },
                    Some(Ordering::Greater) => "downgraded",
                    Some(Ordering::Less) | None => "upgraded",
                };
                server.notify_client(
                    client,
                    ServerGeneral::server_msg(
                        ChatType::CommandInfo,
                        format!("Role for player {} {} to {:?}", alias, verb, desired_role),
                    ),
                );
            },
        };
        // Update player list so the player shows up as moderator in client chat.
        //
        // NOTE: We deliberately choose not to differentiate between moderators and
        // administrators in the player list.
        let is_moderator = desired_role.is_some();
        let msg = ServerGeneral::PlayerListUpdate(PlayerListUpdate::Moderator(uid, is_moderator));
        server.state.notify_players(msg);
        Ok(())
    } else {
        Err(action.help_string())
    }
}

fn handle_tell(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    no_sudo(client, target)?;

    if let (Some(alias), message_opt) = parse_cmd_args!(args, String, ..Vec<String>) {
        let ecs = server.state.ecs();
        let player = find_alias(ecs, &alias)?.0;

        if player == target {
            return Err("You can't /tell yourself.".into());
        }
        let target_uid = uid(server, target, "target")?;
        let player_uid = uid(server, player, "player")?;
        let mode = comp::ChatMode::Tell(player_uid);
        insert_or_replace_component(server, target, mode.clone(), "target")?;
        let msg = if message_opt.is_empty() {
            format!("{} wants to talk to you.", alias)
        } else {
            message_opt.join(" ")
        };
        server.state.send_chat(mode.new_message(target_uid, msg));
        server.notify_client(target, ServerGeneral::ChatMode(mode));
        Ok(())
    } else {
        Err(action.help_string())
    }
}

fn handle_faction(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    no_sudo(client, target)?;

    let factions = server.state.ecs().read_storage();
    if let Some(comp::Faction(faction)) = factions.get(target) {
        let mode = comp::ChatMode::Faction(faction.to_string());
        drop(factions);
        insert_or_replace_component(server, target, mode.clone(), "target")?;
        let msg = args.join(" ");
        if !msg.is_empty() {
            if let Some(uid) = server.state.ecs().read_storage().get(target) {
                server.state.send_chat(mode.new_message(*uid, msg));
            }
        }
        server.notify_client(target, ServerGeneral::ChatMode(mode));
        Ok(())
    } else {
        Err("Please join a faction with /join_faction".into())
    }
}

fn handle_group(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    no_sudo(client, target)?;

    let groups = server.state.ecs().read_storage::<comp::Group>();
    if let Some(group) = groups.get(target) {
        let mode = comp::ChatMode::Group(*group);
        drop(groups);
        insert_or_replace_component(server, target, mode.clone(), "target")?;
        let msg = args.join(" ");
        if !msg.is_empty() {
            if let Some(uid) = server.state.ecs().read_storage().get(target) {
                server.state.send_chat(mode.new_message(*uid, msg));
            }
        }
        server.notify_client(target, ServerGeneral::ChatMode(mode));
        Ok(())
    } else {
        Err("Please create a group first".into())
    }
}

fn handle_group_invite(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    if let Some(target_alias) = parse_cmd_args!(args, String) {
        let target_player = find_alias(server.state.ecs(), &target_alias)?.0;
        let uid = uid(server, target_player, "player")?;

        server
            .state
            .mut_resource::<EventBus<ServerEvent>>()
            .emit_now(ServerEvent::InitiateInvite(target, uid, InviteKind::Group));

        if client != target {
            server.notify_client(
                target,
                ServerGeneral::server_msg(
                    ChatType::CommandInfo,
                    format!("{} has been invited to your group.", target_alias),
                ),
            );
        }

        server.notify_client(
            client,
            ServerGeneral::server_msg(
                ChatType::CommandInfo,
                format!("Invited {} to the group.", target_alias),
            ),
        );
        Ok(())
    } else {
        Err(action.help_string())
    }
}

fn handle_group_kick(
    server: &mut Server,
    _client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    // Checking if leader is already done in group_manip
    if let Some(target_alias) = parse_cmd_args!(args, String) {
        let target_player = find_alias(server.state.ecs(), &target_alias)?.0;
        let uid = uid(server, target_player, "player")?;

        server
            .state
            .mut_resource::<EventBus<ServerEvent>>()
            .emit_now(ServerEvent::GroupManip(target, comp::GroupManip::Kick(uid)));
        Ok(())
    } else {
        Err(action.help_string())
    }
}

fn handle_group_leave(
    server: &mut Server,
    _client: EcsEntity,
    target: EcsEntity,
    _args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    server
        .state
        .mut_resource::<EventBus<ServerEvent>>()
        .emit_now(ServerEvent::GroupManip(target, comp::GroupManip::Leave));
    Ok(())
}

fn handle_group_promote(
    server: &mut Server,
    _client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    // Checking if leader is already done in group_manip
    if let Some(target_alias) = parse_cmd_args!(args, String) {
        let target_player = find_alias(server.state.ecs(), &target_alias)?.0;
        let uid = uid(server, target_player, "player")?;

        server
            .state
            .mut_resource::<EventBus<ServerEvent>>()
            .emit_now(ServerEvent::GroupManip(
                target,
                comp::GroupManip::AssignLeader(uid),
            ));
        Ok(())
    } else {
        Err(action.help_string())
    }
}

fn handle_region(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    no_sudo(client, target)?;

    let mode = comp::ChatMode::Region;
    insert_or_replace_component(server, target, mode.clone(), "target")?;
    let msg = args.join(" ");
    if !msg.is_empty() {
        if let Some(uid) = server.state.ecs().read_storage().get(target) {
            server.state.send_chat(mode.new_message(*uid, msg));
        }
    }
    server.notify_client(target, ServerGeneral::ChatMode(mode));
    Ok(())
}

fn handle_say(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    no_sudo(client, target)?;

    let mode = comp::ChatMode::Say;
    insert_or_replace_component(server, target, mode.clone(), "target")?;
    let msg = args.join(" ");
    if !msg.is_empty() {
        if let Some(uid) = server.state.ecs().read_storage().get(target) {
            server.state.send_chat(mode.new_message(*uid, msg));
        }
    }
    server.notify_client(target, ServerGeneral::ChatMode(mode));
    Ok(())
}

fn handle_world(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    no_sudo(client, target)?;

    let mode = comp::ChatMode::World;
    insert_or_replace_component(server, target, mode.clone(), "target")?;
    let msg = args.join(" ");
    if !msg.is_empty() {
        if let Some(uid) = server.state.ecs().read_storage().get(target) {
            server.state.send_chat(mode.new_message(*uid, msg));
        }
    }
    server.notify_client(target, ServerGeneral::ChatMode(mode));
    Ok(())
}

fn handle_join_faction(
    server: &mut Server,
    _client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    let players = server.state.ecs().read_storage::<comp::Player>();
    if let Some(alias) = players.get(target).map(|player| player.alias.clone()) {
        drop(players);
        let (faction_leave, mode) = if let Some(faction) = parse_cmd_args!(args, String) {
            let mode = comp::ChatMode::Faction(faction.clone());
            insert_or_replace_component(server, target, mode.clone(), "target")?;
            let faction_join = server
                .state
                .ecs()
                .write_storage()
                .insert(target, comp::Faction(faction.clone()))
                .ok()
                .flatten()
                .map(|f| f.0);
            server.state.send_chat(
                ChatType::FactionMeta(faction.clone())
                    .chat_msg(format!("[{}] joined faction ({})", alias, faction)),
            );
            (faction_join, mode)
        } else {
            let mode = comp::ChatMode::default();
            insert_or_replace_component(server, target, mode.clone(), "target")?;
            let faction_leave = server
                .state
                .ecs()
                .write_storage()
                .remove(target)
                .map(|comp::Faction(f)| f);
            (faction_leave, mode)
        };
        if let Some(faction) = faction_leave {
            server.state.send_chat(
                ChatType::FactionMeta(faction.clone())
                    .chat_msg(format!("[{}] left faction ({})", alias, faction)),
            );
        }
        server.notify_client(target, ServerGeneral::ChatMode(mode));
        Ok(())
    } else {
        Err("Could not find your player alias".into())
    }
}

#[cfg(not(feature = "worldgen"))]
fn handle_debug_column(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    _args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    Err("Unsupported without worldgen enabled".into())
}

#[cfg(feature = "worldgen")]
fn handle_debug_column(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    let sim = server.world.sim();
    let calendar = (*server.state.ecs().read_resource::<Calendar>()).clone();
    let sampler = server.world.sample_columns();
    let wpos = if let (Some(x), Some(y)) = parse_cmd_args!(args, i32, i32) {
        Vec2::new(x, y)
    } else {
        let pos = position(server, target, "target")?;
        // FIXME: Deal with overflow, if needed.
        pos.0.xy().map(|x| x as i32)
    };
    let msg_generator = |calendar| {
        let alt = sim.get_interpolated(wpos, |chunk| chunk.alt)?;
        let basement = sim.get_interpolated(wpos, |chunk| chunk.basement)?;
        let water_alt = sim.get_interpolated(wpos, |chunk| chunk.water_alt)?;
        let chaos = sim.get_interpolated(wpos, |chunk| chunk.chaos)?;
        let temp = sim.get_interpolated(wpos, |chunk| chunk.temp)?;
        let humidity = sim.get_interpolated(wpos, |chunk| chunk.humidity)?;
        let rockiness = sim.get_interpolated(wpos, |chunk| chunk.rockiness)?;
        let tree_density = sim.get_interpolated(wpos, |chunk| chunk.tree_density)?;
        let spawn_rate = sim.get_interpolated(wpos, |chunk| chunk.spawn_rate)?;
        let chunk_pos = wpos.map2(TerrainChunkSize::RECT_SIZE, |e, sz: u32| e / sz as i32);
        let chunk = sim.get(chunk_pos)?;
        let col = sampler.get((wpos, server.index.as_index_ref(), Some(calendar)))?;
        let gradient = sim.get_gradient_approx(chunk_pos)?;
        let downhill = chunk.downhill;
        let river = &chunk.river;
        let flux = chunk.flux;
        let path = chunk.path;

        Some(format!(
            r#"wpos: {:?}
alt {:?} ({:?})
water_alt {:?} ({:?})
basement {:?}
river {:?}
gradient {:?}
downhill {:?}
chaos {:?}
flux {:?}
temp {:?}
humidity {:?}
rockiness {:?}
tree_density {:?}
spawn_rate {:?}
path {:?} "#,
            wpos,
            alt,
            col.alt,
            water_alt,
            col.water_level,
            basement,
            river,
            gradient,
            downhill,
            chaos,
            flux,
            temp,
            humidity,
            rockiness,
            tree_density,
            spawn_rate,
            path,
        ))
    };
    if let Some(s) = msg_generator(&calendar) {
        server.notify_client(client, ServerGeneral::server_msg(ChatType::CommandInfo, s));
        Ok(())
    } else {
        Err("Not a pre-generated chunk.".into())
    }
}

#[cfg(not(feature = "worldgen"))]
fn handle_debug_ways(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    _args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    Err("Unsupported without worldgen enabled".into())
}

#[cfg(feature = "worldgen")]
fn handle_debug_ways(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    let sim = server.world.sim();
    let wpos = if let (Some(x), Some(y)) = parse_cmd_args!(args, i32, i32) {
        Vec2::new(x, y)
    } else {
        let pos = position(server, target, "target")?;
        // FIXME: Deal with overflow, if needed.
        pos.0.xy().map(|x| x as i32)
    };
    let msg_generator = || {
        let chunk_pos = wpos.map2(TerrainChunkSize::RECT_SIZE, |e, sz: u32| e / sz as i32);
        let mut ret = String::new();
        for delta in LOCALITY {
            let pos = chunk_pos + delta;
            let chunk = sim.get(pos)?;
            writeln!(ret, "{:?}: {:?}", pos, chunk.path).ok()?;
        }
        Some(ret)
    };
    if let Some(s) = msg_generator() {
        server.notify_client(client, ServerGeneral::server_msg(ChatType::CommandInfo, s));
        Ok(())
    } else {
        Err("Not a pre-generated chunk.".into())
    }
}

fn handle_disconnect_all_players(
    server: &mut Server,
    client: EcsEntity,
    _target: EcsEntity,
    args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    let client_uuid = uuid(server, client, "client")?;
    // Make sure temporary mods/admins can't run this command.
    let _role = real_role(server, client_uuid, "role")?;

    if parse_cmd_args!(args, String).as_deref() != Some("confirm") {
        return Err(
            "Please run the command again with the second argument of \"confirm\" to confirm that \
             you really want to disconnect all players from the server"
                .to_string(),
        );
    }

    let ecs = server.state.ecs();
    let players = &ecs.read_storage::<comp::Player>();

    // TODO: This logging and verification of admin commands would be better moved
    // to a more generic method used for auditing -all- admin commands.

    let player_name = if let Some(player) = players.get(client) {
        &*player.alias
    } else {
        warn!(
            "Failed to get player name for admin who used /disconnect_all_players - ignoring \
             command."
        );
        return Err("You do not exist, so you cannot use this command".to_string());
    };

    info!(
        "Disconnecting all clients due to admin command from {}",
        player_name
    );
    server.disconnect_all_clients_requested = true;

    Ok(())
}

fn handle_skill_point(
    server: &mut Server,
    _client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    if let (Some(a_skill_tree), Some(sp), a_alias) = parse_cmd_args!(args, String, u16, String) {
        let skill_tree = parse_skill_tree(&a_skill_tree)?;
        let player = a_alias
            .map(|alias| find_alias(server.state.ecs(), &alias).map(|(target, _)| target))
            .unwrap_or(Ok(target))?;

        if let Some(mut skill_set) = server
            .state
            .ecs_mut()
            .write_storage::<comp::SkillSet>()
            .get_mut(player)
        {
            skill_set.add_skill_points(skill_tree, sp);
            Ok(())
        } else {
            Err("Player has no stats!".into())
        }
    } else {
        Err(action.help_string())
    }
}

fn parse_skill_tree(skill_tree: &str) -> CmdResult<comp::skillset::SkillGroupKind> {
    use comp::{item::tool::ToolKind, skillset::SkillGroupKind};
    match skill_tree {
        "general" => Ok(SkillGroupKind::General),
        "sword" => Ok(SkillGroupKind::Weapon(ToolKind::Sword)),
        "axe" => Ok(SkillGroupKind::Weapon(ToolKind::Axe)),
        "hammer" => Ok(SkillGroupKind::Weapon(ToolKind::Hammer)),
        "bow" => Ok(SkillGroupKind::Weapon(ToolKind::Bow)),
        "staff" => Ok(SkillGroupKind::Weapon(ToolKind::Staff)),
        "sceptre" => Ok(SkillGroupKind::Weapon(ToolKind::Sceptre)),
        "mining" => Ok(SkillGroupKind::Weapon(ToolKind::Pick)),
        _ => Err(format!("{} is not a skill group!", skill_tree)),
    }
}

fn handle_reload_chunks(
    server: &mut Server,
    _client: EcsEntity,
    _target: EcsEntity,
    _args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    server.state.clear_terrain();

    Ok(())
}

fn handle_remove_lights(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    let opt_radius = parse_cmd_args!(args, f32);
    let player_pos = position(server, target, "target")?;
    let mut to_delete = vec![];

    let ecs = server.state.ecs();
    for (entity, pos, _, _, _) in (
        &ecs.entities(),
        &ecs.read_storage::<comp::Pos>(),
        &ecs.read_storage::<LightEmitter>(),
        !&ecs.read_storage::<WaypointArea>(),
        !&ecs.read_storage::<comp::Player>(),
    )
        .join()
    {
        if opt_radius
            .map(|r| pos.0.distance(player_pos.0) < r)
            .unwrap_or(true)
        {
            to_delete.push(entity);
        }
    }

    let size = to_delete.len();

    for entity in to_delete {
        if let Err(e) = server.state.delete_entity_recorded(entity) {
            error!(?e, "Failed to delete light: {:?}", e);
        }
    }

    server.notify_client(
        client,
        ServerGeneral::server_msg(ChatType::CommandInfo, format!("Removed {} lights!", size)),
    );
    Ok(())
}

fn handle_sudo(
    server: &mut Server,
    client: EcsEntity,
    _target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    if let (Some(player_alias), Some(cmd), cmd_args) =
        parse_cmd_args!(args, String, String, ..Vec<String>)
    {
        if let Ok(action) = cmd.parse() {
            let (player, player_uuid) = find_alias(server.state.ecs(), &player_alias)?;
            let client_uuid = uuid(server, client, "client")?;
            verify_above_role(
                server,
                (client, client_uuid),
                (player, player_uuid),
                "Cannot sudo players with roles higher than your own.",
            )?;

            // TODO: consider making this into a tail call or loop (to avoid the potential
            // stack overflow, although it's less of a risk coming from only mods and
            // admins).
            do_command(server, client, player, cmd_args, &action)
        } else {
            Err(format!("Unknown command: /{}", cmd))
        }
    } else {
        Err(action.help_string())
    }
}

fn handle_version(
    server: &mut Server,
    client: EcsEntity,
    _target: EcsEntity,
    _args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    server.notify_client(
        client,
        ServerGeneral::server_msg(
            ChatType::CommandInfo,
            format!(
                "Server is running {}[{}]",
                *common::util::GIT_HASH,
                *common::util::GIT_DATE,
            ),
        ),
    );
    Ok(())
}

fn handle_whitelist(
    server: &mut Server,
    client: EcsEntity,
    _target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    let now = Utc::now();

    if let (Some(whitelist_action), Some(username)) = parse_cmd_args!(args, String, String) {
        let client_uuid = uuid(server, client, "client")?;
        let client_username = uuid_to_username(server, client, client_uuid)?;
        let client_role = real_role(server, client_uuid, "client")?;

        if whitelist_action.eq_ignore_ascii_case("add") {
            let uuid = find_username(server, &username)?;

            let record = WhitelistRecord {
                date: now,
                info: Some(WhitelistInfo {
                    username_when_whitelisted: username.clone(),
                    whitelisted_by: client_uuid,
                    whitelisted_by_username: client_username,
                    whitelisted_by_role: client_role.into(),
                }),
            };

            let edit =
                server
                    .editable_settings_mut()
                    .whitelist
                    .edit(server.data_dir().as_ref(), |w| {
                        if w.insert(uuid, record).is_some() {
                            None
                        } else {
                            Some(format!("added to whitelist: {}", username))
                        }
                    });
            edit_setting_feedback(server, client, edit, || {
                format!("already in whitelist: {}!", username)
            })
        } else if whitelist_action.eq_ignore_ascii_case("remove") {
            let client_uuid = uuid(server, client, "client")?;
            let client_role = real_role(server, client_uuid, "client")?;

            let uuid = find_username(server, &username)?;
            let mut err_info = "not part of whitelist: ";
            let edit =
                server
                    .editable_settings_mut()
                    .whitelist
                    .edit(server.data_dir().as_ref(), |w| {
                        w.remove(&uuid)
                            .filter(|record| {
                                if record.whitelisted_by_role() <= client_role.into() {
                                    true
                                } else {
                                    err_info = "permission denied to remove user: ";
                                    false
                                }
                            })
                            .map(|_| format!("removed from whitelist: {}", username))
                    });
            edit_setting_feedback(server, client, edit, || format!("{}{}", err_info, username))
        } else {
            Err(action.help_string())
        }
    } else {
        Err(action.help_string())
    }
}

fn kick_player(
    server: &mut Server,
    (client, client_uuid): (EcsEntity, Uuid),
    (target_player, target_player_uuid): (EcsEntity, Uuid),
    reason: &str,
) -> CmdResult<()> {
    verify_above_role(
        server,
        (client, client_uuid),
        (target_player, target_player_uuid),
        "Cannot kick players with roles higher than your own.",
    )?;
    server.notify_client(
        target_player,
        ServerGeneral::Disconnect(DisconnectReason::Kicked(reason.to_string())),
    );
    server
        .state
        .mut_resource::<EventBus<ServerEvent>>()
        .emit_now(ServerEvent::ClientDisconnect(
            target_player,
            comp::DisconnectReason::Kicked,
        ));
    Ok(())
}

fn handle_kick(
    server: &mut Server,
    client: EcsEntity,
    _target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    if let (Some(target_alias), reason_opt) = parse_cmd_args!(args, String, String) {
        let client_uuid = uuid(server, client, "client")?;
        let reason = reason_opt.unwrap_or_default();
        let ecs = server.state.ecs();
        let target_player = find_alias(ecs, &target_alias)?;

        kick_player(server, (client, client_uuid), target_player, &reason)?;
        server.notify_client(
            client,
            ServerGeneral::server_msg(
                ChatType::CommandInfo,
                format!(
                    "Kicked {} from the server with reason: {}",
                    target_alias, reason
                ),
            ),
        );
        Ok(())
    } else {
        Err(action.help_string())
    }
}

fn handle_ban(
    server: &mut Server,
    client: EcsEntity,
    _target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    if let (Some(username), overwrite, parse_duration, reason_opt) =
        parse_cmd_args!(args, String, bool, HumanDuration, String)
    {
        let reason = reason_opt.unwrap_or_default();
        let overwrite = overwrite.unwrap_or(false);

        let player_uuid = find_username(server, &username)?;

        let client_uuid = uuid(server, client, "client")?;
        let client_username = uuid_to_username(server, client, client_uuid)?;
        let client_role = real_role(server, client_uuid, "client")?;

        let now = Utc::now();
        let end_date = parse_duration
            .map(|duration| chrono::Duration::from_std(duration.into()))
            .transpose()
            .map_err(|err| format!("Error converting to duration: {}", err))?
            // On overflow (someone adding some ridiculous time span), just make the ban infinite.
            .and_then(|duration| now.checked_add_signed(duration));

        let ban_info = BanInfo {
            performed_by: client_uuid,
            performed_by_username: client_username,
            performed_by_role: client_role.into(),
        };

        let ban = Ban {
            reason: reason.clone(),
            info: Some(ban_info),
            end_date,
        };

        let edit = server
            .editable_settings_mut()
            .banlist
            .ban_action(
                server.data_dir().as_ref(),
                now,
                player_uuid,
                username.clone(),
                BanAction::Ban(ban),
                overwrite,
            )
            .map(|result| {
                (
                    format!("Added {} to the banlist with reason: {}", username, reason),
                    result,
                )
            });

        edit_setting_feedback(server, client, edit, || {
            format!("{} is already on the banlist", username)
        })?;
        // If the player is online kick them (this may fail if the player is a hardcoded
        // admin; we don't care about that case because hardcoded admins can log on even
        // if they're on the ban list).
        let ecs = server.state.ecs();
        if let Ok(target_player) = find_uuid(ecs, player_uuid) {
            let _ = kick_player(
                server,
                (client, client_uuid),
                (target_player, player_uuid),
                &reason,
            );
        }
        Ok(())
    } else {
        Err(action.help_string())
    }
}

fn handle_battlemode(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    // TODO: discuss time
    const COOLDOWN: f64 = 60.0 * 5.0;

    let ecs = server.state.ecs();
    let time = ecs.read_resource::<Time>();
    let settings = ecs.read_resource::<Settings>();
    if let Some(mode) = parse_cmd_args!(args, String) {
        if !settings.gameplay.battle_mode.allow_choosing() {
            return Err("Command disabled in server settings".to_owned());
        }

        #[cfg(feature = "worldgen")]
        let in_town = {
            // get chunk position
            let pos = position(server, target, "target")?;
            let wpos = pos.0.xy().map(|x| x as i32);
            let chunk_pos = wpos.map2(TerrainChunkSize::RECT_SIZE, |wpos, size: u32| {
                wpos / size as i32
            });
            server.world.civs().sites().any(|site| {
                // empirical
                const RADIUS: f32 = 9.0;
                let delta = site
                    .center
                    .map(|x| x as f32)
                    .distance(chunk_pos.map(|x| x as f32));
                delta < RADIUS
            })
        };
        // just skip this check, if worldgen is disabled
        #[cfg(not(feature = "worldgen"))]
        let in_town = true;

        if !in_town {
            return Err("You need to be in town to change battle mode!".to_owned());
        }

        let mut players = ecs.write_storage::<comp::Player>();
        let mut player_info = players.get_mut(target).ok_or_else(|| {
            error!("Can't get player component for player");
            "Error!"
        })?;
        if let Some(Time(last_change)) = player_info.last_battlemode_change {
            let Time(time) = *time;
            let elapsed = time - last_change;
            if elapsed < COOLDOWN {
                let msg = format!(
                    "Cooldown period active. Try again in {:.0} seconds",
                    COOLDOWN - elapsed,
                );
                return Err(msg);
            }
        }
        let mode = match mode.as_str() {
            "pvp" => BattleMode::PvP,
            "pve" => BattleMode::PvE,
            _ => return Err("Available modes: pvp, pve".to_owned()),
        };
        if player_info.battle_mode == mode {
            return Err("Attempted to set the same battlemode".to_owned());
        }
        player_info.battle_mode = mode;
        player_info.last_battlemode_change = Some(*time);
        server.notify_client(
            client,
            ServerGeneral::server_msg(
                ChatType::CommandInfo,
                format!("New battle mode: {:?}", mode),
            ),
        );
        Ok(())
    } else {
        let players = ecs.read_storage::<comp::Player>();
        let player = players.get(target).ok_or_else(|| {
            error!("Can't get player component for player");
            "Error!"
        })?;
        let mut msg = format!("Current battle mode: {:?}.", player.battle_mode);
        if settings.gameplay.battle_mode.allow_choosing() {
            msg.push_str(" Possible to change.");
        } else {
            msg.push_str(" Global.");
        }
        if let Some(change) = player.last_battlemode_change {
            let Time(time) = *time;
            let Time(change) = change;
            let elapsed = time - change;
            let next = COOLDOWN - elapsed;
            let notice = format!(" Next change will be available in: {:.0} seconds", next);
            msg.push_str(&notice);
        }
        server.notify_client(
            client,
            ServerGeneral::server_msg(ChatType::CommandInfo, msg),
        );
        Ok(())
    }
}

fn handle_battlemode_force(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    let ecs = server.state.ecs();
    let settings = ecs.read_resource::<Settings>();
    if !settings.gameplay.battle_mode.allow_choosing() {
        return Err("Command disabled in server settings".to_owned());
    }
    let mode = parse_cmd_args!(args, String).ok_or_else(|| action.help_string())?;
    let mode = match mode.as_str() {
        "pvp" => BattleMode::PvP,
        "pve" => BattleMode::PvE,
        _ => return Err("Available modes: pvp, pve".to_owned()),
    };
    let mut players = ecs.write_storage::<comp::Player>();
    let mut player_info = players
        .get_mut(target)
        .ok_or("Cannot get player component for target")?;
    player_info.battle_mode = mode;
    server.notify_client(
        client,
        ServerGeneral::server_msg(
            ChatType::CommandInfo,
            format!("Set battle mode to: {:?}", mode),
        ),
    );
    Ok(())
}

fn handle_unban(
    server: &mut Server,
    client: EcsEntity,
    _target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    if let Some(username) = parse_cmd_args!(args, String) {
        let player_uuid = find_username(server, &username)?;

        let client_uuid = uuid(server, client, "client")?;
        let client_username = uuid_to_username(server, client, client_uuid)?;
        let client_role = real_role(server, client_uuid, "client")?;

        let now = Utc::now();

        let ban_info = BanInfo {
            performed_by: client_uuid,
            performed_by_username: client_username,
            performed_by_role: client_role.into(),
        };

        let unban = BanAction::Unban(ban_info);

        let edit = server
            .editable_settings_mut()
            .banlist
            .ban_action(
                server.data_dir().as_ref(),
                now,
                player_uuid,
                username.clone(),
                unban,
                false,
            )
            .map(|result| (format!("{} was successfully unbanned", username), result));

        edit_setting_feedback(server, client, edit, || {
            format!("{} was already unbanned", username)
        })
    } else {
        Err(action.help_string())
    }
}

fn handle_server_physics(
    server: &mut Server,
    client: EcsEntity,
    _target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    if let (Some(username), enabled_opt) = parse_cmd_args!(args, String, bool) {
        let uuid = find_username(server, &username)?;
        let server_force = enabled_opt.unwrap_or(true);

        let mut player_physics_settings =
            server.state.ecs().write_resource::<PlayerPhysicsSettings>();
        let entry = player_physics_settings.settings.entry(uuid).or_default();
        entry.server_force = server_force;

        server.notify_client(
            client,
            ServerGeneral::server_msg(
                ChatType::CommandInfo,
                format!(
                    "Updated physics settings for {} ({}): {:?}",
                    username, uuid, entry
                ),
            ),
        );
        Ok(())
    } else {
        Err(action.help_string())
    }
}

fn handle_apply_buff(
    server: &mut Server,
    _client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    if let (Some(buff), strength, duration) = parse_cmd_args!(args, String, f32, f64) {
        let strength = strength.unwrap_or(0.01);
        let duration = Duration::from_secs_f64(duration.unwrap_or(1.0));
        let buffdata = BuffData::new(strength, Some(duration));
        if buff != "all" {
            cast_buff(&buff, buffdata, server, target)
        } else {
            for kind in BUFF_PACK.iter() {
                cast_buff(kind, buffdata, server, target)?;
            }
            Ok(())
        }
    } else {
        Err(action.help_string())
    }
}

fn cast_buff(kind: &str, data: BuffData, server: &mut Server, target: EcsEntity) -> CmdResult<()> {
    if let Some(buffkind) = parse_buffkind(kind) {
        let ecs = &server.state.ecs();
        let mut buffs_all = ecs.write_storage::<comp::Buffs>();
        if let Some(mut buffs) = buffs_all.get_mut(target) {
            buffs.insert(Buff::new(buffkind, data, vec![], BuffSource::Command));
        }
        Ok(())
    } else {
        Err(format!("unknown buff: {}", kind))
    }
}

fn parse_buffkind(buff: &str) -> Option<BuffKind> { BUFF_PARSER.get(buff).copied() }

fn handle_skill_preset(
    server: &mut Server,
    _client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    if let Some(preset) = parse_cmd_args!(args, String) {
        if let Some(mut skill_set) = server
            .state
            .ecs_mut()
            .write_storage::<comp::SkillSet>()
            .get_mut(target)
        {
            match preset.as_str() {
                "clear" => {
                    clear_skillset(&mut skill_set);
                    Ok(())
                },
                preset => set_skills(&mut skill_set, preset),
            }
        } else {
            Err("Player has no stats!".into())
        }
    } else {
        Err(action.help_string())
    }
}

fn clear_skillset(skill_set: &mut comp::SkillSet) { *skill_set = comp::SkillSet::default(); }

fn set_skills(skill_set: &mut comp::SkillSet, preset: &str) -> CmdResult<()> {
    let presets = match common::cmd::SkillPresetManifest::load(PRESET_MANIFEST_PATH) {
        Ok(presets) => presets.read().0.clone(),
        Err(err) => {
            warn!("Error in preset: {}", err);
            return Err("Error while loading presets".to_owned());
        },
    };
    if let Some(preset) = presets.get(preset) {
        for (skill, level) in preset {
            let group = if let Some(group) = skill.skill_group_kind() {
                group
            } else {
                warn!("Skill in preset doesn't exist in any group");
                return Err("Preset is broken".to_owned());
            };
            for _ in 0..*level {
                let cost = skill_set.skill_cost(*skill);
                skill_set.add_skill_points(group, cost);
                match skill_set.unlock_skill(*skill) {
                    Ok(_) | Err(comp::skillset::SkillUnlockError::SkillAlreadyUnlocked) => Ok(()),
                    Err(err) => Err(format!("{:?}", err)),
                }?;
            }
        }
        Ok(())
    } else {
        Err("Such preset doesn't exist".to_owned())
    }
}

fn handle_location(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    if let Some(name) = parse_cmd_args!(args, String) {
        let loc = server.state.ecs().read_resource::<Locations>().get(&name);
        match loc {
            Ok(loc) => position_mut(server, target, "target", |target_pos| {
                target_pos.0 = loc;
            }),
            Err(e) => Err(e.to_string()),
        }
    } else {
        let locations = server.state.ecs().read_resource::<Locations>();
        let mut locations = locations.iter().map(|s| s.as_str()).collect::<Vec<_>>();
        locations.sort_unstable();
        server.notify_client(
            client,
            ServerGeneral::server_msg(
                ChatType::CommandInfo,
                if locations.is_empty() {
                    "No locations currently exist".to_owned()
                } else {
                    format!("Available locations:\n{}", locations.join(", "))
                },
            ),
        );
        Ok(())
    }
}

fn handle_create_location(
    server: &mut Server,
    client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    if let Some(name) = parse_cmd_args!(args, String) {
        let target_pos = position(server, target, "target")?;

        let res = server
            .state
            .ecs_mut()
            .write_resource::<Locations>()
            .insert(name.clone(), target_pos.0);
        match res {
            Ok(()) => {
                server.notify_client(
                    client,
                    ServerGeneral::server_msg(
                        ChatType::CommandInfo,
                        format!("Created location '{}'", name),
                    ),
                );
                Ok(())
            },
            Err(e) => Err(e.to_string()),
        }
    } else {
        Err(action.help_string())
    }
}

fn handle_delete_location(
    server: &mut Server,
    client: EcsEntity,
    _target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    if let Some(name) = parse_cmd_args!(args, String) {
        let res = server
            .state
            .ecs_mut()
            .write_resource::<Locations>()
            .remove(&name);
        match res {
            Ok(()) => {
                server.notify_client(
                    client,
                    ServerGeneral::server_msg(
                        ChatType::CommandInfo,
                        format!("Deleted location '{}'", name),
                    ),
                );
                Ok(())
            },
            Err(e) => Err(e.to_string()),
        }
    } else {
        Err(action.help_string())
    }
}

fn handle_weather_zone(
    server: &mut Server,
    client: EcsEntity,
    _target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    if let (Some(name), radius, time) = parse_cmd_args!(args, String, f32, f32) {
        let radius = radius.map(|r| r / weather::CELL_SIZE as f32).unwrap_or(1.0);
        let time = time.unwrap_or(100.0);

        let mut add_zone = |weather: weather::Weather| {
            if let Ok(pos) = position(server, client, "player") {
                let pos = pos.0.xy() / weather::CELL_SIZE as f32;
                server
                    .state
                    .ecs_mut()
                    .write_resource::<WeatherSim>()
                    .add_zone(weather, pos, radius, time);
            }
        };
        match name.as_str() {
            "clear" => {
                add_zone(weather::Weather {
                    cloud: 0.0,
                    rain: 0.0,
                    wind: Vec2::zero(),
                });
                Ok(())
            },
            "cloudy" => {
                add_zone(weather::Weather {
                    cloud: 0.4,
                    rain: 0.0,
                    wind: Vec2::zero(),
                });
                Ok(())
            },
            "rain" => {
                add_zone(weather::Weather {
                    cloud: 0.1,
                    rain: 0.15,
                    wind: Vec2::new(1.0, -1.0),
                });
                Ok(())
            },
            "wind" => {
                add_zone(weather::Weather {
                    cloud: 0.0,
                    rain: 0.0,
                    wind: Vec2::new(10.0, 10.0),
                });
                Ok(())
            },
            "storm" => {
                add_zone(weather::Weather {
                    cloud: 0.3,
                    rain: 0.3,
                    wind: Vec2::new(15.0, 20.0),
                });
                Ok(())
            },
            _ => Err("Valid values are 'clear', 'rain', 'wind', 'storm'".to_string()),
        }
    } else {
        Err(action.help_string())
    }
}

fn handle_lightning(
    server: &mut Server,
    client: EcsEntity,
    _target: EcsEntity,
    _args: Vec<String>,
    _action: &ServerChatCommand,
) -> CmdResult<()> {
    let pos = position(server, client, "player")?.0;
    server
        .state
        .ecs()
        .read_resource::<EventBus<Outcome>>()
        .emit_now(Outcome::Lightning { pos });
    Ok(())
}

fn handle_body(
    server: &mut Server,
    _client: EcsEntity,
    target: EcsEntity,
    args: Vec<String>,
    action: &ServerChatCommand,
) -> CmdResult<()> {
    if let Some(npc::NpcBody(_id, mut body)) = parse_cmd_args!(args, npc::NpcBody) {
        let body = body();
        insert_or_replace_component(server, target, body, "body")?;
        insert_or_replace_component(server, target, body.mass(), "mass")?;
        insert_or_replace_component(server, target, body.density(), "density")?;
        insert_or_replace_component(server, target, body.collider(), "collider")?;
        Ok(())
    } else {
        Err(action.help_string())
    }
}