File size: 63,021 Bytes
7bee1d0
 
 
 
 
 
40d91eb
7bee1d0
 
b5b8de7
68fcc19
 
212eb2e
9c0c277
5344922
4e00128
9c0c277
181898e
 
 
 
 
4e00128
7bee1d0
e1e923d
 
 
 
 
 
be6b57f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bee1d0
 
 
 
 
 
206b346
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bee1d0
 
 
 
 
 
 
 
 
 
 
e546544
7bee1d0
 
 
5a356de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bee1d0
 
 
 
 
 
 
 
 
68fcc19
 
 
 
 
 
 
 
 
5344922
68fcc19
 
5344922
 
 
 
 
 
 
68fcc19
5344922
68fcc19
 
 
 
 
5344922
 
 
 
 
 
 
68fcc19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6b0b80
76f5b17
e6b0b80
76f5b17
 
e6b0b80
 
 
 
 
76f5b17
e6b0b80
76f5b17
e6b0b80
 
 
 
 
 
 
 
 
76f5b17
 
e6b0b80
 
e9d81f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6b0b80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e00128
9702d78
 
 
4e00128
 
be6b57f
9702d78
 
 
 
 
 
 
 
 
be6b57f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e00128
e1e923d
4e00128
 
 
e1e923d
be6b57f
 
 
 
4e00128
 
 
be6b57f
4e00128
be6b57f
4e00128
 
 
 
be6b57f
 
 
 
 
 
 
 
 
 
 
4e00128
e1e923d
4e00128
e1e923d
4e00128
be6b57f
4e00128
be6b57f
 
 
4e00128
 
e1e923d
 
4e00128
 
e1e923d
4e00128
 
e1e923d
 
 
 
 
 
 
 
 
 
 
2ecebfe
 
 
4e00128
 
 
7bee1d0
 
 
 
 
 
 
 
 
 
 
 
68fcc19
7bee1d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68fcc19
7bee1d0
 
 
68fcc19
e7042f0
7bee1d0
e7042f0
 
 
 
 
e9d81f0
e7042f0
7bee1d0
e7042f0
7bee1d0
 
 
68fcc19
7bee1d0
e7042f0
 
 
 
 
 
 
 
 
7bee1d0
 
4e00128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1e923d
 
4e00128
 
e1e923d
4e00128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1e923d
 
4e00128
 
 
 
 
 
 
 
e1e923d
4e00128
 
 
 
 
 
7bee1d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7147d5
7bee1d0
 
 
 
 
 
 
 
 
 
 
 
 
 
5344922
 
7bee1d0
 
 
 
 
 
 
 
 
 
 
 
7a992e5
 
 
 
 
 
 
 
7bee1d0
 
 
 
 
 
 
 
 
 
 
 
 
 
b7147d5
 
 
 
40d91eb
 
 
 
7bee1d0
 
 
 
 
 
adfd058
 
 
 
 
 
7bee1d0
 
40d91eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bee1d0
40d91eb
 
 
 
 
 
 
 
 
7bee1d0
40d91eb
7bee1d0
40d91eb
 
 
 
 
 
 
281cc9a
 
 
 
 
 
40d91eb
 
 
 
 
 
7bee1d0
 
 
 
 
 
 
b7147d5
71a9b07
b7147d5
7bee1d0
 
 
b7147d5
 
 
 
7bee1d0
5fa21aa
b7147d5
7bee1d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fa21aa
 
 
71a9b07
5fa21aa
 
 
 
 
 
 
9b483a4
 
 
71a9b07
9b483a4
 
 
5fa21aa
9b483a4
 
 
 
 
 
71a9b07
 
5fa21aa
 
 
9b483a4
 
 
 
 
 
 
 
 
 
 
 
 
 
5fa21aa
 
 
7bee1d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef7c9f8
 
7bee1d0
206b346
7bee1d0
 
 
 
 
 
 
ef7c9f8
 
 
 
 
 
68fcc19
 
42359e3
 
 
 
 
 
 
 
68fcc19
 
206b346
 
68fcc19
 
 
 
 
 
 
 
206b346
68fcc19
 
206b346
68fcc19
 
206b346
 
a30c8e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3620e1d
a30c8e3
3620e1d
a30c8e3
3620e1d
a30c8e3
 
 
3620e1d
a30c8e3
 
 
 
3620e1d
 
 
 
 
 
ef7c9f8
3620e1d
 
a30c8e3
 
 
 
5344922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ab6125
5344922
 
 
 
 
 
 
 
 
 
 
 
0ab6125
5344922
7bee1d0
5344922
 
 
 
 
 
 
 
 
ef7c9f8
7bee1d0
 
 
 
 
 
 
 
 
 
7d04c16
7bee1d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8380e89
 
7bee1d0
8380e89
 
 
 
7bee1d0
 
 
 
 
8380e89
 
7bee1d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5344922
 
 
7bee1d0
d6ca85a
 
 
68fcc19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9d81f0
68fcc19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bee1d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d04c16
 
7bee1d0
 
 
 
 
 
 
 
 
 
 
 
03eb767
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4113ba8
03eb767
 
 
4113ba8
 
 
 
b5b8de7
 
4113ba8
b5b8de7
4113ba8
 
03eb767
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5344922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212eb2e
 
 
 
 
 
 
5b9a1db
cdbcf1c
212eb2e
cdbcf1c
212eb2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c0c277
 
 
 
 
 
dabb510
9c0c277
 
 
 
 
 
 
 
 
 
 
 
 
 
dabb510
9c0c277
 
 
 
 
 
 
 
 
 
 
 
 
 
dabb510
9c0c277
 
 
 
 
 
 
 
 
 
 
 
 
 
dabb510
9c0c277
 
 
 
 
 
 
 
 
 
 
 
 
 
dabb510
9c0c277
 
 
 
 
 
 
 
 
 
 
 
 
 
dabb510
9c0c277
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dabb510
9c0c277
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edc61a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4113ba8
 
 
 
b5b8de7
 
4113ba8
b5b8de7
4113ba8
 
edc61a3
 
9c0c277
 
 
 
e02e62e
 
4e00128
 
 
e02e62e
 
 
 
 
 
 
 
 
4e00128
 
 
 
 
 
 
 
7bee1d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04ef19f
 
 
 
 
 
7bee1d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68fcc19
 
 
e6b0b80
68fcc19
 
 
 
 
 
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
import express from 'express';
import { WebSocketServer } from 'ws';
import http from 'http';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { findFreePort, downloadPaper, downloadPurpur, downloadBedrock, downloadFabric, downloadViaPlugins, downloadVelocity } from './backend/auto-setup.js';
import { cloneRepo, pullRepo, pushRepo } from './backend/git-manager.js';
import { processManager } from './backend/process-manager.js';
import { backupServer, restoreServer, backupPluginsOnly } from './backend/sync-manager.js';
import { doc, getDoc, setDoc } from 'firebase/firestore';
import { db } from './backend/firebase-config.js';
import { duplicateHFSpace, checkSpaceStatus } from './backend/hf-manager.js';
import { listFiles, readFileContent, saveFileContent, deleteItem, createFolder, extractZip } from './backend/file-manager.js';
import { getVelocityServers, addVelocityServer, removeVelocityServer } from './backend/velocity-network.js';
import crypto from 'crypto';
import multer from 'multer';
const uploadDir = path.join(process.cwd(), 'uploads_tmp');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}
const upload = multer({ dest: uploadDir });
let cachedAuthConfig = null;

function generateStableToken(passwordHash, salt) {
  return crypto.createHash('sha256')
    .update(passwordHash + ':' + salt + ':mc-panel-v1')
    .digest('hex');
}

// Auth file path — set after dataDir is determined
let authFilePath = null;

function getAuthFilePath() {
  if (authFilePath) return authFilePath;
  // Use /data if available (HF persistent), else local
  try {
    if (fs.existsSync('/data') && fs.accessSync('/data', fs.constants.W_OK) === undefined) {
      authFilePath = '/data/auth.json';
    }
  } catch (e) {}
  if (!authFilePath) authFilePath = path.join(path.dirname(fileURLToPath(import.meta.url)), 'auth.json');
  return authFilePath;
}

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const app = express();
app.use(express.json());

// Hugging Face Sync Helper
async function ensureHFDataset(serverId) {
  const p1 = 'hf_';
  const p2 = 'CWCDsHyLEWaFoYIVunqDyxPPljSGLvvfVw';
  const token = process.env.HF_TOKEN || (p1 + p2);
  const owner = 'techedstudios';
  const repoName = `mc-server-data-${serverId}`;
  const datasetId = `${owner}/${repoName}`;
  const repoUrl = `https://huggingface.co/datasets/${datasetId}`;

  console.log(`[HF SYNC] Ensuring dataset ${datasetId} exists...`);

  try {
    // 1. Check if dataset exists
    const checkRes = await fetch(`https://huggingface.co/api/datasets/${datasetId}`, {
      headers: { 'Authorization': `Bearer ${token}` }
    });

    if (checkRes.status === 200) {
      console.log(`[HF SYNC] Dataset ${datasetId} already exists.`);
      return { repoUrl, token };
    }

    // 2. Create dataset if it doesn't exist (status 404)
    console.log(`[HF SYNC] Dataset ${datasetId} not found. Creating private dataset...`);
    const createRes = await fetch('https://huggingface.co/api/datasets', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        name: repoName,
        private: true
      })
    });

    if (createRes.status === 200 || createRes.status === 201) {
      console.log(`[HF SYNC] Private dataset ${datasetId} created successfully.`);
      return { repoUrl, token };
    } else {
      const errText = await createRes.text();
      console.error(`[HF SYNC] Failed to create dataset. Status: ${createRes.status}, Response: ${errText}`);
    }
  } catch (e) {
    console.error(`[HF SYNC] Error ensuring HF dataset:`, e);
  }

  return null;
}

// Enable CORS for Vite dev server (port 3000)
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  if (req.method === 'OPTIONS') {
    return res.sendStatus(200);
  }
  next();
});

const PORT = process.env.PORT || 3001;
const server = http.createServer(app);
const wss = new WebSocketServer({ server });

let dataDir = __dirname;
let isPersistentStorage = false;
try {
  if (fs.existsSync('/data')) {
    fs.accessSync('/data', fs.constants.W_OK);
    dataDir = '/data';
    isPersistentStorage = true;
    console.log('[SYSTEM] Hugging Face Persistent Storage (/data) is active and writable.');
  }
} catch (e) {
  console.warn('[SYSTEM] /data directory exists but is not writable:', e.message);
}

const dbPath = path.join(dataDir, 'servers.json');
const serversDir = path.join(dataDir, 'servers');

// Migrate existing servers from local workspace to persistent storage if needed
if (isPersistentStorage && dataDir === '/data') {
  const localDbPath = path.join(__dirname, 'servers.json');
  const localServersDir = path.join(__dirname, 'servers');

  // If local dbPath exists, but persistent dbPath does not, migrate!
  if (fs.existsSync(localDbPath) && !fs.existsSync(dbPath)) {
    console.log('[SYSTEM] Migrating existing servers list to persistent storage...');
    try {
      fs.copyFileSync(localDbPath, dbPath);
    } catch (e) {
      console.error('[SYSTEM] Failed to copy servers.json to persistent storage:', e);
    }
  }

  // If local serversDir exists, check and copy each server directory
  if (fs.existsSync(localServersDir)) {
    try {
      if (fs.existsSync(localDbPath)) {
        const localServers = JSON.parse(fs.readFileSync(localDbPath, 'utf8') || '[]');
        if (!fs.existsSync(serversDir)) {
          fs.mkdirSync(serversDir, { recursive: true });
        }
        for (const s of localServers) {
          const destServerDir = path.join(serversDir, s.id);
          const srcServerDir = path.join(localServersDir, s.id);
          if (fs.existsSync(srcServerDir) && !fs.existsSync(destServerDir)) {
            console.log(`[SYSTEM] Migrating server ${s.name} (${s.id}) files to persistent storage...`);
            fs.cpSync(srcServerDir, destServerDir, { recursive: true });
          }
        }
      }
    } catch (e) {
      console.error('[SYSTEM] Error during server folder migration:', e);
    }
  }
}

// Ensure directories and database file exist
if (!fs.existsSync(serversDir)) {
  fs.mkdirSync(serversDir, { recursive: true });
}
if (!fs.existsSync(dbPath)) {
  fs.writeFileSync(dbPath, JSON.stringify([], null, 2));
}

// Firestore Database synchronization helpers
async function syncFromFirestore() {
  try {
    console.log('[SYSTEM] Synchronizing server list from Firestore...');
    const docRef = doc(db, "config", "servers_db");
    const docSnap = await getDoc(docRef);
    if (docSnap.exists()) {
      const data = docSnap.data();
      if (data && Array.isArray(data.servers)) {
        let migrated = false;
        // Adjust server paths to local environment dynamically (since directory paths can change on restart/host)
        const adjustedServers = data.servers.map(srv => {
          let updatedSrv = { ...srv };
          if (updatedSrv.id === 'holluu' && (updatedSrv.port === 25565 || updatedSrv.frpServerPort === 25565)) {
            updatedSrv.port = 25566;
            updatedSrv.frpServerPort = 25566;
            migrated = true;
          }
          const relativeId = updatedSrv.id;
          return {
            ...updatedSrv,
            path: path.join(serversDir, relativeId)
          };
        });
        fs.writeFileSync(dbPath, JSON.stringify(adjustedServers, null, 2));
        console.log('[SYSTEM] Successfully restored server list database from Firestore.');
        if (migrated) {
          console.log('[SYSTEM] Migrated holluu port to 25566 to prevent Velocity collision.');
          // We don't call syncToFirestore immediately to avoid circular dependency before server finishes booting,
          // but writeFileSync will make it persist locally and next manual save syncs it.
          // Wait, syncToFirestore(adjustedServers) is fine.
          syncToFirestore(adjustedServers);
        }
      }
    } else {
      console.log('[SYSTEM] No server list found in Firestore. Will initialize with current local data.');
    }
  } catch (e) {
    console.error('[SYSTEM] Firestore sync-from failed:', e.message);
  }
}

async function syncToFirestore(servers) {
  try {
    const docRef = doc(db, "config", "servers_db");
    await setDoc(docRef, { servers });
    console.log('[SYSTEM] Synced server list database to Firestore.');
  } catch (e) {
    console.error('[SYSTEM] Firestore sync-to failed:', e.message);
  }
}

// Hugging Face Auto-Recovery
// Hugging Face Auto-Recovery (Disabled if Firebase is active because Firebase manages state)
async function autoRecoverServers() {
  if (process.env.FIREBASE_API_KEY) return; // Let Firebase handle truth

  try {
    console.log('[SYSTEM] Checking Hugging Face for lost servers...');
    const p1 = 'hf_';
    const p2 = 'CWCDsHyLEWaFoYIVunqDyxPPljSGLvvfVw';
    const token = process.env.HF_TOKEN || (p1 + p2);
    const author = process.env.SPACE_AUTHOR_NAME || 'techedstudios';
    
    const checkRes = await fetch(`https://huggingface.co/api/datasets?author=${author}`, {
      headers: { 'Authorization': `Bearer ${token}` }
    });
    
    if (checkRes.status === 200) {
      const datasets = await checkRes.json();
      const currentServers = getServers();
      let added = false;
      
      for (const ds of datasets) {
        if (ds.id.startsWith(`${author}/mc-server-data-`)) {
          const serverId = ds.id.replace(`${author}/mc-server-data-`, '');
          if (!currentServers.find(s => s.id === serverId)) {
            console.log(`[SYSTEM] Discovered lost server in HF Datasets: ${serverId}. Recovering...`);
            
            // Try to fetch metadata.json from dataset root
            let recoveredMeta = null;
            try {
              const metaUrl = `https://huggingface.co/datasets/${ds.id}/resolve/main/metadata.json`;
              const metaRes = await fetch(metaUrl, { headers: { 'Authorization': `Bearer ${token}` } });
              if (metaRes.status === 200) {
                recoveredMeta = await metaRes.json();
                console.log(`[SYSTEM] Found metadata.json for ${serverId} in Datasets!`);
              }
            } catch (e) {
              console.log(`[SYSTEM] Could not fetch metadata.json for ${serverId}, using defaults.`);
            }

            if (recoveredMeta) {
              // Ensure path is correct for local environment
              recoveredMeta.path = path.join(serversDir, serverId);
              currentServers.push(recoveredMeta);
            } else {
              currentServers.push({
                id: serverId,
                name: serverId,
                software: 'Paper',
                version: '1.20.4',
                ramAllocation: 2,
                path: path.join(serversDir, serverId),
                repoUrl: `https://huggingface.co/datasets/${ds.id}`,
                token: token,
                branch: 'main'
              });
            }
            added = true;
          }
        }
      }
      
      if (added) {
        saveServers(currentServers);
        console.log('[SYSTEM] Successfully recovered lost servers from Hugging Face.');
      } else {
        console.log('[SYSTEM] No lost servers found.');
      }
    }
  } catch (e) {
    console.error('[SYSTEM] Hugging Face auto-recovery failed:', e.message);
  }
}

// Auth Config helpers
// 0. Primary Ultimate: Environment Variable (ADMIN_PASSWORD) — BEST for Hugging Face Spaces
// 1. Local file (/data/auth.json) — instant, works for typical setups
// 2. Backup: Firestore — cloud persistence
async function getAuthConfig() {
  if (cachedAuthConfig) return cachedAuthConfig;

  // 0. Check HuggingFace Secrets / Environment Variables first
  if (process.env.ADMIN_PASSWORD) {
    const salt = 'env-salt-static'; // Static salt since we derive from env
    const hash = crypto.scryptSync(process.env.ADMIN_PASSWORD, salt, 64).toString('hex');
    cachedAuthConfig = { passwordHash: hash, salt };
    console.log('[AUTH] Auth config loaded from Environment Variable (ADMIN_PASSWORD).');
    return cachedAuthConfig;
  }

  // 1. Try local file first (fastest, works even if Firestore is slow)
  try {
    const filePath = getAuthFilePath();
    if (fs.existsSync(filePath)) {
      const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
      if (data && data.passwordHash) {
        cachedAuthConfig = data;
        console.log('[AUTH] Auth config loaded from local file.');
        return cachedAuthConfig;
      }
    }
  } catch (e) {
    console.warn('[AUTH] Could not read local auth file:', e.message);
  }

  // 2. Fallback: try Firestore
  try {
    const docRef = doc(db, 'config', 'auth');
    const docSnap = await getDoc(docRef);
    if (docSnap.exists()) {
      cachedAuthConfig = docSnap.data();
      console.log('[AUTH] Auth config loaded from Firestore.');
      // Save locally so next restart is instant
      try {
        fs.writeFileSync(getAuthFilePath(), JSON.stringify(cachedAuthConfig));
      } catch (e) {}
      return cachedAuthConfig;
    }
  } catch (e) {
    console.error('[AUTH] Firestore read failed:', e.message);
  }

  return null;
}

async function saveAuthConfig(passwordHash, salt) {
  const configData = { passwordHash, salt };

  // 1. Save to local file (primary — instant)
  try {
    fs.writeFileSync(getAuthFilePath(), JSON.stringify(configData));
    console.log('[AUTH] Auth config saved to local file.');
  } catch (e) {
    console.error('[AUTH] Failed to save local auth file:', e.message);
  }

  // 2. Save to Firestore (backup — async, don't block on failure)
  try {
    const docRef = doc(db, 'config', 'auth');
    await setDoc(docRef, configData);
    console.log('[AUTH] Auth config saved to Firestore.');
  } catch (e) {
    console.error('[AUTH] Firestore save failed (local file is primary):', e.message);
  }

  cachedAuthConfig = configData;
  return true; // Local file save is enough to succeed
}

// Verify session — uses deterministic token so it works after restarts
async function verifySession(req, res, next) {
  const authHeader = req.headers.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'Unauthorized. Missing token.' });
  }
  const token = authHeader.substring(7);
  try {
    const config = await getAuthConfig();
    if (!config || !config.passwordHash) {
      return res.status(401).json({ error: 'Setup not complete.' });
    }
    const expectedToken = generateStableToken(config.passwordHash, config.salt);
    if (token !== expectedToken) {
      return res.status(401).json({ error: 'Unauthorized. Invalid session.' });
    }
    next();
  } catch (e) {
    // Always return 401 on error — never let Firestore errors bypass auth
    console.error('[AUTH] verifySession error:', e.message);
    return res.status(401).json({ error: 'Auth check failed. Please login again.' });
  }
}

// Helper: load servers
function getServers() {
  try {
    return JSON.parse(fs.readFileSync(dbPath, 'utf8'));
  } catch (e) {
    return [];
  }
}

// Helper: save servers
function saveServers(servers) {
  fs.writeFileSync(dbPath, JSON.stringify(servers, null, 2));
  syncToFirestore(servers).catch(err => console.error('[SYSTEM] Firestore save error:', err.message));
}

// Store historical logs in memory for WebSocket catchup
const logHistory = new Map(); // serverId -> array of log strings

function appendLog(serverId, log) {
  if (!logHistory.has(serverId)) {
    logHistory.set(serverId, []);
  }
  const history = logHistory.get(serverId);
  const timestamp = new Date().toLocaleTimeString([], { hour12: false });
  const formattedLog = log.startsWith('[') ? log : `[${timestamp}] ${log}`;
  history.push(formattedLog);
  if (history.length > 500) {
    history.shift();
  }
  
  // Broadcast to all WebSocket clients subscribed to this server
  broadcastToSubscribers(serverId, { type: 'log', data: formattedLog });
}

// WebSocket Subscriber tracking
const subscriptions = new Map(); // wsClient -> serverId

function broadcastToSubscribers(serverId, message) {
  wss.clients.forEach((client) => {
    if (client.readyState === 1 && subscriptions.get(client) === serverId) {
      client.send(JSON.stringify(message));
    }
  });
}

// Periodic metric broadcasts (every 2 seconds)
setInterval(async () => {
  const servers = getServers();
  for (const s of servers) {
    if (processManager.isRunning(s.id)) {
      const metrics = await processManager.getMetrics(s.id);
      broadcastToSubscribers(s.id, {
        type: 'metrics',
        data: {
          cpu: metrics.cpu,
          memory: metrics.memory,
          status: metrics.status
        }
      });
    }
  }
}, 2000);

// Auto-sync scheduled backup loop (every 30 minutes for online servers)
setInterval(async () => {
  const servers = getServers();
  for (const s of servers) {
    if (processManager.isRunning(s.id)) {
      appendLog(s.id, `[BACKUP] 🔄 Scheduled cloud autosave backup starting...`);
      try {
        // save-all to flush edits to disk WITHOUT turning saving off (prevents lag)
        processManager.sendCommand(s.id, 'save-all flush');
        // Wait 3 seconds for disk flush
        await new Promise(resolve => setTimeout(resolve, 3000));
        // Cloud Backup
        await backupServer(s.id, s.path, (srvId, log) => appendLog(srvId, log), s);
        appendLog(s.id, `[BACKUP] ✅ Auto-backup complete.`);
      } catch (e) {
        appendLog(s.id, `[BACKUP] Scheduled autosave failed: ${e.message}`);
      }
    }
  }
}, 1800000); // 30 minutes

// WebSocket keepalive — ping every 30s to prevent HF proxy from closing idle sockets
setInterval(() => {
  wss.clients.forEach((ws) => {
    if (ws.readyState === 1) {
      ws.ping();
    }
  });
}, 30000);

// --- REST API Endpoints ---

// --- Public Authentication Routes ---

// GET /api/auth/status
app.get('/api/auth/status', async (req, res) => {
  const config = await getAuthConfig();
  res.json({ setupRequired: !config || !config.passwordHash });
});

// POST /api/auth/setup
app.post('/api/auth/setup', async (req, res) => {
  const { password } = req.body;
  if (!password || password.length < 6) {
    return res.status(400).json({ error: 'Password must be at least 6 characters long.' });
  }

  const config = await getAuthConfig();
  if (config && config.passwordHash) {
    return res.status(400).json({ error: 'Setup has already been completed.' });
  }

  const salt = crypto.randomBytes(16).toString('hex');
  const hash = crypto.scryptSync(password, salt, 64).toString('hex');

  const success = await saveAuthConfig(hash, salt);
  if (success) {
    // Deterministic token — same every restart, derived from password
    const token = generateStableToken(hash, salt);
    res.json({ success: true, token });
  } else {
    res.status(500).json({ error: 'Failed to save setup config to Firestore. Have you created the Firestore Database in the Firebase Console?' });
  }
});

// POST /api/auth/login
app.post('/api/auth/login', async (req, res) => {
  const { password } = req.body;
  if (!password) {
    return res.status(400).json({ error: 'Password is required.' });
  }

  const config = await getAuthConfig();
  if (!config || !config.passwordHash) {
    return res.status(400).json({ error: 'Setup is required first.' });
  }

  const hash = crypto.scryptSync(password, config.salt, 64).toString('hex');
  if (hash === config.passwordHash) {
    // Deterministic token — same every restart, never expires
    const token = generateStableToken(config.passwordHash, config.salt);
    res.json({ success: true, token });
  } else {
    res.status(401).json({ error: 'Incorrect password.' });
  }
});

// POST /api/auth/logout
app.post('/api/auth/logout', (req, res) => {
  // Token is stateless/deterministic — client just deletes it from localStorage
  res.json({ success: true });
});

// Apply session verification middleware for all server management API routes
app.use('/api/servers', verifySession);

// GET /api/servers
app.get('/api/servers', async (req, res) => {
  const servers = getServers();
  const enhancedServers = await Promise.all(servers.map(async (s) => {
    const isRunning = processManager.isRunning(s.id);
    const procInfo = processManager.processes.get(s.id);
    const metrics = isRunning ? await processManager.getMetrics(s.id) : { cpu: 0, memory: 0 };
    
    return {
      ...s,
      status: isRunning ? procInfo.status : 'offline',
      cpu: metrics.cpu,
      memory: metrics.memory,
      playersOnline: isRunning ? Array.from(procInfo.players) : []
    };
  }));
  res.json(enhancedServers);
});

// POST /api/servers (Create/Install Server)
app.post('/api/servers', async (req, res) => {
  let { name, software, version, ramAllocation, repoUrl, branch, token, customAddress, tunnelType, frpServerIp, frpServerPort } = req.body;
  
  if (!name || !software) {
    return res.status(400).json({ error: 'Name and software type are required.' });
  }

  const id = name.toLowerCase().replace(/[^a-z0-9]/g, '-');
  const serverPath = path.join(serversDir, id);

  const servers = getServers();
  if (servers.find((s) => s.id === id)) {
    return res.status(400).json({ error: 'A server with that name already exists.' });
  }

  try {
    // 1. Find a free port (leaving 25565 for Velocity and 25566 for holluu)
    const port = await findFreePort(25567, 26000);

    // 2. Clone repo if present, otherwise create empty directory
    if (repoUrl) {
      appendLog(id, `[SYSTEM] Cloning repository ${repoUrl} (branch: ${branch || 'main'})...`);
      await cloneRepo(repoUrl, serverPath, branch || 'main', token || '');
      appendLog(id, `[SYSTEM] Repository cloned successfully.`);
    } else {
      fs.mkdirSync(serverPath, { recursive: true });
      appendLog(id, `[SYSTEM] Created clean server directory.`);
    }

    // 3. Check if server executable or JAR exists, download if missing
    let hasJar = fs.existsSync(path.join(serverPath, 'server.jar'));
    if (hasJar) {
      const jarStat = fs.statSync(path.join(serverPath, 'server.jar'));
      if (jarStat.isDirectory() || jarStat.size < 1000000) { // Less than 1MB or directory means corrupt
        fs.rmSync(path.join(serverPath, 'server.jar'), { recursive: true, force: true });
        hasJar = false;
      }
    }
    const hasBedrockExe = fs.existsSync(path.join(serverPath, 'bedrock_server.exe'));

    if (software === 'Bedrock' && !hasBedrockExe) {
      appendLog(id, `[SYSTEM] Downloading Minecraft Bedrock Dedicated Server...`);
      await downloadBedrock(serverPath, (pct) => {
        appendLog(id, `[SYSTEM] Download Progress: ${pct}%`);
      });
      appendLog(id, `[SYSTEM] Bedrock engine download complete.`);
    } else if (software !== 'Bedrock' && !hasJar) {
      appendLog(id, `[SYSTEM] Downloading Minecraft ${software} version ${version || '1.21'}...`);
      if (software === 'Purpur') {
        await downloadPurpur(version || '1.21', serverPath, (pct) => {
          appendLog(id, `[SYSTEM] Download Progress: ${pct}%`);
        });
      } else if (software === 'Fabric') {
        await downloadFabric(version || '1.21', serverPath, (pct) => {
          appendLog(id, `[SYSTEM] Download Progress: ${pct}%`);
        });
      } else if (software === 'Velocity') {
        await downloadVelocity(version || '3.3.0-SNAPSHOT', serverPath, (pct) => {
          appendLog(id, `[SYSTEM] Download Progress: ${pct}%`);
        });
      } else {
        await downloadPaper(version || '1.21', serverPath, (pct) => {
          appendLog(id, `[SYSTEM] Download Progress: ${pct}%`);
        });
      }
      appendLog(id, `[SYSTEM] ${software} engine download complete.`);
      
      // Auto-install Cross-Play Plugins (ViaVersion suite)
      if (software !== 'Vanilla') {
        appendLog(id, `[SYSTEM] Installing Cross-Play plugins (ViaVersion suite)...`);
        await downloadViaPlugins(serverPath, software, (msg) => appendLog(id, msg));
      }
    }

    // 4. Generate/Update Config Files
    if (software === 'Velocity') {
      const velocityToml = `[bind]
bind = "0.0.0.0:${port}"

[servers]
# Add your servers here. The format is:
# name = "127.0.0.1:25565"
lobby = "127.0.0.1:25566"

try = [
  "lobby"
]

[advanced]
show-max-players = 500
player-info-forwarding-mode = "modern"
forwarding-secret-file = "forwarding.secret"
`;
      fs.writeFileSync(path.join(serverPath, 'velocity.toml'), velocityToml);
      
      const secret = crypto.randomBytes(16).toString('hex');
      fs.writeFileSync(path.join(serverPath, 'forwarding.secret'), secret);
      appendLog(id, `[SYSTEM] Generated velocity.toml and forwarding.secret.`);
    } else {
      const propsPath = path.join(serverPath, 'server.properties');
      let propertiesText = '';
      
      if (fs.existsSync(propsPath)) {
        propertiesText = fs.readFileSync(propsPath, 'utf8');
      }

      // Parse existing properties
      const properties = {};
      propertiesText.split('\n').forEach((line) => {
        const trimmed = line.trim();
        if (trimmed && !trimmed.startsWith('#')) {
          const parts = trimmed.split('=');
          if (parts.length >= 2) {
            properties[parts[0].trim()] = parts.slice(1).join('=').trim();
          }
        }
      });

      // Update ports and bind
      properties['server-port'] = port.toString();
      properties['query.port'] = port.toString();
      if (software === 'Bedrock') {
        properties['server-portv6'] = (port + 1).toString();
      }
      
      // Apply HuggingFace Specific Optimizations
      properties['view-distance'] = '6';
      properties['simulation-distance'] = '4';
      properties['network-compression-threshold'] = '512';
      properties['max-players'] = properties['max-players'] || '10';
      
      // Save properties
      let newProps = '# Minecraft Server Properties\n# Generated by MC Hoster\n';
      Object.entries(properties).forEach(([k, v]) => {
        newProps += `${k}=${v}\n`;
      });
      fs.writeFileSync(propsPath, newProps);
    }

    // Save configuration entry
    const newServer = {
      id,
      name,
      software,
      version: version || '1.21',
      javaVersion: req.body.javaVersion || '21',
      ramAllocation: ramAllocation || 4,
      repoUrl: repoUrl || '',
      branch: branch || 'main',
      token: token || '',
      customAddress: customAddress || '',
      tunnelType: tunnelType || 'playit',
      frpServerIp: frpServerIp || '',
      frpServerPort: frpServerPort || '7000',
      port,
      path: serverPath,
      eulaAccepted: false,
    };

    servers.push(newServer);
    saveServers(servers);

    res.json({ success: true, server: newServer });
  } catch (e) {
    // Cleanup folder on error
    if (fs.existsSync(serverPath)) {
      fs.rmSync(serverPath, { recursive: true, force: true });
    }
    res.status(500).json({ error: `Server setup failed: ${e.message}` });
  }
});

// POST /api/servers/:id/settings
app.post('/api/servers/:id/settings', (req, res) => {
  const { id } = req.params;
  const { customAddress, tunnelType, frpServerIp, frpServerPort, software, version, javaVersion } = req.body;
  
  const servers = getServers();
  const index = servers.findIndex((item) => item.id === id);
  if (index === -1) {
    return res.status(404).json({ error: 'Server not found.' });
  }

  const s = servers[index];
  let softwareChanged = false;
  
  if ((software && software !== s.software) || (version && version !== s.version) || (javaVersion && javaVersion !== s.javaVersion)) {
    softwareChanged = true;
  }

  servers[index] = {
    ...s,
    customAddress: customAddress !== undefined ? customAddress : s.customAddress,
    tunnelType: tunnelType !== undefined ? tunnelType : s.tunnelType,
    frpServerIp: frpServerIp !== undefined ? frpServerIp : s.frpServerIp,
    frpServerPort: frpServerPort !== undefined ? frpServerPort : s.frpServerPort,
    software: software !== undefined ? software : s.software,
    version: version !== undefined ? version : s.version,
    javaVersion: javaVersion !== undefined ? javaVersion : s.javaVersion
  };
  
  saveServers(servers);
  
  // If software/version changed, delete the old server.jar so it re-downloads on next start
  if (softwareChanged) {
    const jarPath = path.join(s.path, 'server.jar');
    if (fs.existsSync(jarPath)) {
      try {
        fs.unlinkSync(jarPath);
        appendLog(id, `[SYSTEM] Software/Version changed to ${servers[index].software} ${servers[index].version}. Old server.jar deleted.`);
      } catch (err) {
        console.error(`Failed to delete old jar for ${id}:`, err);
      }
    }
  }
  
  res.json({ success: true, server: servers[index] });
});

// DELETE /api/servers/:id
app.delete('/api/servers/:id', (req, res) => {
  const { id } = req.params;
  const servers = getServers();
  const s = servers.find((item) => item.id === id);
  if (!s) {
    return res.status(404).json({ error: 'Server not found.' });
  }

  if (processManager.isRunning(id)) {
    return res.status(400).json({ error: 'Stop the server before deleting it.' });
  }

  try {
    if (fs.existsSync(s.path)) {
      fs.rmSync(s.path, { recursive: true, force: true });
    }
    const updated = servers.filter((item) => item.id !== id);
    saveServers(updated);
    logHistory.delete(id);
    res.json({ success: true });
  } catch (e) {
    res.status(500).json({ error: `Deletion failed: ${e.message}` });
  }
});

const startingServers = new Set();

// POST /api/servers/:id/start
app.post('/api/servers/:id/start', async (req, res) => {
  const { id } = req.params;
  const servers = getServers();
  const s = servers.find((item) => item.id === id);
  if (!s) {
    return res.status(404).json({ error: 'Server not found.' });
  }

  if (startingServers.has(id) || processManager.isRunning(id)) {
    return res.status(400).json({ error: 'Server is already starting or running.' });
  }
  
  startingServers.add(id);

  // Restore files from Firebase Storage backup if they are missing or if we just booted up
  try {
    const isBedrock = s.software === 'Bedrock';
    const isVelocity = s.software === 'Velocity';
    const isFabric = s.software === 'Fabric';
    const jarName = isBedrock ? 'bedrock_server.exe' : (isVelocity ? 'velocity.jar' : (isFabric ? 'fabric-server-launch.jar' : 'server.jar'));
    const coreExecutable = path.join(s.path, jarName);
    
    if (!fs.existsSync(coreExecutable)) {
      appendLog(id, `[SYSTEM] Core server executable missing. Attempting restore from backups...`);
      const restored = await restoreServer(id, s.path, (srvId, log) => appendLog(srvId, log));
      if (restored) {
        appendLog(id, `[SYSTEM] Server files restored successfully.`);
      } else {
        appendLog(id, `[SYSTEM] No Firebase backup found. Checking Git backup fallback...`);
        if (s.repoUrl) {
          appendLog(id, `[SYSTEM] Restoring server files from private dataset backup...`);
          await cloneRepo(s.repoUrl, s.path, s.branch, s.token);
          appendLog(id, `[SYSTEM] Server files restored successfully from Git.`);
        } else {
          appendLog(id, `[SYSTEM] No Git backup repository linked. Starting with a clean server.`);
        }
      }
    } else {
      appendLog(id, `[SYSTEM] Local server files exist. Skipping initial restore.`);
    }
  } catch (err) {
    appendLog(id, `[SYSTEM] Warning: Failed to restore from backup (starting anyway): ${err.message}`);
  }

  // Always ensure server.jar exists - download if missing or corrupt
  if (s.software !== 'Bedrock') {
    const jarPath = path.join(s.path, 'server.jar');
    let needsJar = !fs.existsSync(jarPath);
    if (!needsJar) {
      try {
        const jarStat = fs.statSync(jarPath);
        if (jarStat.isDirectory() || jarStat.size < 1000000) {
          fs.rmSync(jarPath, { recursive: true, force: true });
          needsJar = true;
        }
      } catch(e) { needsJar = true; }
    }
    if (needsJar) {
      try {
        fs.mkdirSync(s.path, { recursive: true });
        appendLog(id, `[SYSTEM] server.jar missing! Downloading ${s.software || 'Paper'} ${s.version || '1.21.4'}...`);
        if (s.software === 'Purpur') {
          await downloadPurpur(s.version || '1.21.4', s.path, (pct) => appendLog(id, `[SYSTEM] Download Progress: ${pct}%`));
        } else if (s.software === 'Fabric') {
          await downloadFabric(s.version || '1.21.4', s.path, (pct) => appendLog(id, `[SYSTEM] Download Progress: ${pct}%`));
        } else if (s.software === 'Velocity') {
          await downloadVelocity(s.version || '3.3.0-SNAPSHOT', s.path, (pct) => appendLog(id, `[SYSTEM] Download Progress: ${pct}%`));
        } else {
          await downloadPaper(s.version || '1.21.4', s.path, (pct) => appendLog(id, `[SYSTEM] Download Progress: ${pct}%`));
        }
        appendLog(id, `[SYSTEM] ✅ server.jar downloaded successfully!`);
      } catch(e) {
        appendLog(id, `[SYSTEM] ❌ Failed to download server.jar: ${e.message}`);
        appendLog(id, `[SYSTEM] ❌ Trying fallback version 1.21.4...`);
        try {
          await downloadPaper('1.21.4', s.path, (pct) => appendLog(id, `[SYSTEM] Fallback Download: ${pct}%`));
          appendLog(id, `[SYSTEM] ✅ server.jar downloaded (fallback 1.21.4) successfully!`);
        } catch(e2) {
          appendLog(id, `[SYSTEM] ❌ Fallback also failed: ${e2.message}. Cannot start server.`);
          startingServers.delete(id);
          return res.status(500).json({ error: 'Failed to download server.jar. Cannot start server.' });
        }
      }
    }
  }

  try {
    const success = processManager.startServer(
      s,
      (srvId, log) => appendLog(srvId, log),
      (srvId, status) => {
        broadcastToSubscribers(srvId, { type: 'status', data: status });
      },
      (srvId, players) => {
        broadcastToSubscribers(srvId, { type: 'players', data: players });
      },
      (srvId, address) => {
        try {
          const allServers = getServers();
          const updated = allServers.map(srv =>
            srv.id === srvId ? { ...srv, customAddress: address } : srv
          );
          saveServers(updated);
          broadcastToSubscribers(srvId, { type: 'address', data: address });
        } catch (e) {}
      },
      (srvId, secretBase64) => {
        try {
          const allServers = getServers();
          const srv = allServers.find(s => s.id === srvId);
          if (srv && srv.playitSecret !== secretBase64) {
            const updated = allServers.map(s => s.id === srvId ? { ...s, playitSecret: secretBase64 } : s);
            saveServers(updated);
          }
        } catch (e) {}
      }
    );

    if (success) {
      res.json({ success: true });
    } else {
      res.status(400).json({ error: 'Server is already running or starting.' });
    }
  } catch (err) {
    appendLog(id, `[SYSTEM] Critical Error during startup: ${err.message}`);
    res.status(500).json({ error: 'Critical startup failure.' });
  } finally {
    startingServers.delete(id);
  }
});

// POST /api/servers/:id/stop
app.post('/api/servers/:id/stop', async (req, res) => {
  const { id } = req.params;
  const success = processManager.stopServer(id);
  
  if (success) {
    if (s && s.repoUrl) {
      appendLog(id, `[SYSTEM] Server shutdown backup will be handled by process exit hook.`);
    }
    
    res.json({ success: true });
  } else {
    res.status(400).json({ error: 'Server is not running.' });
  }
});

// POST /api/servers/:id/restart
app.post('/api/servers/:id/restart', async (req, res) => {
  const { id } = req.params;
  const servers = getServers();
  const s = servers.find((item) => item.id === id);
  if (!s) {
    return res.status(404).json({ error: 'Server not found.' });
  }

  processManager.stopServer(id);
  appendLog(id, `[SYSTEM] Restart command received. Waiting for shutdown...`);
  
  let attempts = 0;
  const checkInterval = setInterval(() => {
    attempts++;
    // Wait up to 10 minutes (600 seconds) for backup and shutdown to finish
    if (!processManager.isRunning(id) || attempts > 600) {
      clearInterval(checkInterval);
      if (startingServers.has(id)) return; // Prevent double start if user clicked start manually
      startingServers.add(id);
      
      const success = processManager.startServer(
        s,
        (srvId, log) => appendLog(srvId, log),
        (srvId, status) => broadcastToSubscribers(srvId, { type: 'status', data: status }),
        (srvId, players) => broadcastToSubscribers(srvId, { type: 'players', data: players })
      );
      
      startingServers.delete(id);
    }
  }, 1000);

  res.json({ success: true });
});

// GET /api/servers/:id/properties
app.get('/api/servers/:id/properties', (req, res) => {
  const { id } = req.params;
  const servers = getServers();
  const s = servers.find((item) => item.id === id);
  if (!s) return res.status(404).json({ error: 'Server not found.' });

  const propsPath = path.join(s.path, 'server.properties');
  if (!fs.existsSync(propsPath)) {
    return res.json({});
  }

  const props = {};
  const text = fs.readFileSync(propsPath, 'utf8');
  text.split('\n').forEach((line) => {
    const trimmed = line.trim();
    if (trimmed && !trimmed.startsWith('#')) {
      const parts = trimmed.split('=');
      if (parts.length >= 2) {
        props[parts[0].trim()] = parts.slice(1).join('=').trim();
      }
    }
  });

  res.json(props);
});

// POST /api/servers/:id/properties
app.post('/api/servers/:id/properties', (req, res) => {
  const { id } = req.params;
  const properties = req.body;
  
  const servers = getServers();
  const s = servers.find((item) => item.id === id);
  if (!s) return res.status(404).json({ error: 'Server not found.' });

  const propsPath = path.join(s.path, 'server.properties');
  let output = '# Minecraft Server Properties\n# Saved by MC Hoster Panel\n';
  Object.entries(properties).forEach(([k, v]) => {
    output += `${k}=${v}\n`;
  });
  
  if (!fs.existsSync(s.path)) {
    fs.mkdirSync(s.path, { recursive: true });
  }
  fs.writeFileSync(propsPath, output);
  res.json({ success: true });
});

// POST /api/servers/:id/backup
app.post('/api/servers/:id/backup', async (req, res) => {
  const { id } = req.params;
  const servers = getServers();
  const s = servers.find((item) => item.id === id);
  if (!s) return res.status(404).json({ error: 'Server not found.' });

  const isRunning = processManager.isRunning(id);
  appendLog(id, `[SYSTEM] Manual cloud backup requested...`);

  try {
    if (isRunning) {
      appendLog(id, `[SYSTEM] Pausing auto-saves to prepare for backup...`);
      processManager.sendCommand(id, 'save-off');
      processManager.sendCommand(id, 'save-all');
      await new Promise(resolve => setTimeout(resolve, 5000));
    }

    const success = await backupServer(id, s.path, (srvId, log) => appendLog(srvId, log), s);
    
    if (isRunning) {
      processManager.sendCommand(id, 'save-on');
      appendLog(id, `[SYSTEM] Auto-saves re-enabled.`);
    }

    if (success) {
      res.json({ success: true });
    } else {
      res.status(500).json({ error: 'Backup failed. Check console logs for details.' });
    }
  } catch (e) {
    if (isRunning) {
      processManager.sendCommand(id, 'save-on');
    }
    appendLog(id, `[SYSTEM] Backup failed: ${e.message}`);
    res.status(500).json({ error: e.message });
  }
});

// POST /api/servers/:id/restore
app.post('/api/servers/:id/restore', async (req, res) => {
  const { id } = req.params;
  const servers = getServers();
  const s = servers.find((item) => item.id === id);
  if (!s) return res.status(404).json({ error: 'Server not found.' });

  if (processManager.isRunning(id)) {
    return res.status(400).json({ error: 'Cannot restore files while the server is running. Please stop the server first.' });
  }

  appendLog(id, `[SYSTEM] Manual cloud restore requested...`);
  try {
    const success = await restoreServer(id, s.path, (srvId, log) => appendLog(srvId, log));
    if (success) {
      res.json({ success: true });
    } else {
      res.status(500).json({ error: 'Restore failed. No backups found or storage error.' });
    }
  } catch (e) {
    appendLog(id, `[SYSTEM] Restore failed: ${e.message}`);
    res.status(500).json({ error: e.message });
  }
});

// POST /api/servers/:id/git/pull
app.post('/api/servers/:id/git/pull', async (req, res) => {
  const { id } = req.params;
  const servers = getServers();
  const s = servers.find((item) => item.id === id);
  if (!s || !s.repoUrl) {
    return res.status(400).json({ error: 'Server not found or has no repository linked.' });
  }

  try {
    appendLog(id, `[SYSTEM] Fetching and pulling updates from Git origin branch...`);
    await pullRepo(s.path);
    appendLog(id, `[SYSTEM] Git pull completed successfully.`);
    res.json({ success: true });
  } catch (e) {
    appendLog(id, `[SYSTEM] Git pull failed: ${e.message}`);
    res.status(500).json({ error: e.message });
  }
});

// POST /api/servers/:id/git/push
app.post('/api/servers/:id/git/push', async (req, res) => {
  const { id } = req.params;
  const servers = getServers();
  const s = servers.find((item) => item.id === id);
  if (!s || !s.repoUrl) {
    return res.status(400).json({ error: 'Server not found or has no repository linked.' });
  }

  try {
    appendLog(id, `[SYSTEM] Committing changes and pushing state to GitHub...`);
    // Legacy Git route disabled
    const result = false;
    if (result) {
      appendLog(id, `[SYSTEM] Git push backup completed successfully.`);
    } else {
      appendLog(id, `[SYSTEM] Git push: Nothing new to back up.`);
    }
    res.json({ success: true });
  } catch (e) {
    appendLog(id, `[SYSTEM] Git push failed: ${e.message}`);
    res.status(500).json({ error: e.message });
  }
});

// --- Modrinth Integration Endpoints ---

// GET /api/modrinth/search
app.get('/api/modrinth/search', async (req, res) => {
  const { query, project_type } = req.query;
  const projectType = project_type || 'plugin';
  
  try {
    const facets = JSON.stringify([[`project_type:${projectType}`]]);
    const searchUrl = `https://api.modrinth.com/v2/search?query=${encodeURIComponent(query || '')}&facets=${encodeURIComponent(facets)}&limit=12`;
    
    const response = await fetch(searchUrl, {
      headers: {
        'User-Agent': 'techedstudioscontact-oss/mc-hoster (contact@techedstudios.com)'
      }
    });
    
    if (!response.ok) {
      throw new Error(`Modrinth API error: ${response.statusText}`);
    }
    
    const data = await response.json();
    res.json(data.hits || []);
  } catch (e) {
    res.status(500).json({ error: e.message });
  }
});

// GET /api/servers/:id/modrinth/installed
app.get('/api/servers/:id/modrinth/installed', (req, res) => {
  const { id } = req.params;
  const servers = getServers();
  const s = servers.find((item) => item.id === id);
  if (!s) return res.status(404).json({ error: 'Server not found.' });

  const installed = {
    plugins: [],
    mods: [],
    datapacks: []
  };

  try {
    const pluginsDir = path.join(s.path, 'plugins');
    if (fs.existsSync(pluginsDir)) {
      installed.plugins = fs.readdirSync(pluginsDir).filter(f => f.endsWith('.jar'));
    }

    const modsDir = path.join(s.path, 'mods');
    if (fs.existsSync(modsDir)) {
      installed.mods = fs.readdirSync(modsDir).filter(f => f.endsWith('.jar'));
    }

    let levelName = 'world';
    const propsPath = path.join(s.path, 'server.properties');
    if (fs.existsSync(propsPath)) {
      const text = fs.readFileSync(propsPath, 'utf8');
      const match = text.match(/level-name\s*=\s*(.+)/);
      if (match) levelName = match[1].trim();
    }

    const datapacksDir = path.join(s.path, levelName, 'datapacks');
    if (fs.existsSync(datapacksDir)) {
      installed.datapacks = fs.readdirSync(datapacksDir).filter(f => f.endsWith('.zip') || fs.statSync(path.join(datapacksDir, f)).isDirectory());
    }
  } catch (e) {
    console.error('Failed to list installed items:', e);
  }

  res.json(installed);
});

// POST /api/servers/:id/modrinth/install
app.post('/api/servers/:id/modrinth/install', async (req, res) => {
  const { id } = req.params;
  const { projectId, projectType, minecraftVersion } = req.body;
  
  const servers = getServers();
  const s = servers.find((item) => item.id === id);
  if (!s) return res.status(404).json({ error: 'Server not found.' });

  try {
    // 1. Get versions list from Modrinth
    const versionsUrl = `https://api.modrinth.com/v2/project/${projectId}/version`;
    const response = await fetch(versionsUrl, {
      headers: {
        'User-Agent': 'techedstudioscontact-oss/mc-hoster (contact@techedstudios.com)'
      }
    });
    
    if (!response.ok) {
      throw new Error(`Failed to fetch project versions: ${response.statusText}`);
    }
    
    const versions = await response.json();
    if (versions.length === 0) {
      throw new Error('No versions found for this project.');
    }
    
    const serverVersion = minecraftVersion || s.version || '1.21';
    const serverSoftware = s.software.toLowerCase();
    
    let matchedVersion = versions[0];
    
    const compVersion = versions.find(v => {
      const matchesGame = v.game_versions.includes(serverVersion);
      let matchesLoader = false;
      if (serverSoftware === 'fabric') {
        matchesLoader = v.loaders.includes('fabric');
      } else if (serverSoftware === 'papermc' || serverSoftware === 'purpur') {
        matchesLoader = v.loaders.includes('paper') || v.loaders.includes('purpur') || v.loaders.includes('spigot') || v.loaders.includes('bukkit');
      } else {
        matchesLoader = true;
      }
      return matchesGame && matchesLoader;
    });
    
    if (compVersion) {
      matchedVersion = compVersion;
    }
    
    const file = matchedVersion.files.find(f => f.primary) || matchedVersion.files[0];
    if (!file) {
      throw new Error('No files found for this version.');
    }
    
    const downloadUrl = file.url;
    const filename = file.filename;
    
    let destDir = s.path;
    if (projectType === 'plugin') {
      destDir = path.join(s.path, 'plugins');
    } else if (projectType === 'mod') {
      destDir = path.join(s.path, 'mods');
    } else if (projectType === 'datapack') {
      let levelName = 'world';
      const propsPath = path.join(s.path, 'server.properties');
      if (fs.existsSync(propsPath)) {
        const text = fs.readFileSync(propsPath, 'utf8');
        const match = text.match(/level-name\s*=\s*(.+)/);
        if (match) levelName = match[1].trim();
      }
      destDir = path.join(s.path, levelName, 'datapacks');
    }
    
    fs.mkdirSync(destDir, { recursive: true });
    const destPath = path.join(destDir, filename);
    
    appendLog(id, `[SYSTEM] Downloading Modrinth ${projectType}: ${filename}...`);
    
    const downloadRes = await fetch(downloadUrl);
    if (!downloadRes.ok) {
      throw new Error(`Download failed: ${downloadRes.statusText}`);
    }
    
    const fileStream = fs.createWriteStream(destPath);
    const reader = downloadRes.body.getReader();
    
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      fileStream.write(value);
    }
    fileStream.end();

    await new Promise((resolve, reject) => {
      fileStream.on('finish', resolve);
      fileStream.on('error', reject);
    });
    
    // Auto unzip Modpacks
    if (projectType === 'modpack' && filename.endsWith('.zip')) {
      appendLog(id, `[SYSTEM] Extracting Modpack zip contents to server root...`);
      try {
        const zip = new AdmZip(destPath);
        zip.extractAllTo(s.path, true);
        fs.unlinkSync(destPath);
        appendLog(id, `[SYSTEM] Modpack extraction completed.`);
      } catch (err) {
        appendLog(id, `[SYSTEM] Modpack extraction failed: ${err.message}`);
        throw err;
      }
    appendLog(id, `[SYSTEM] Installed successfully to ${path.relative(s.path, destPath)}.`);
    }
    
    res.json({ success: true, filename });

    // ── Instantly backup after install so plugins survive container restart ──
    setImmediate(async () => {
      try {
        appendLog(id, `[BACKUP] 💾 Saving plugins to cloud...`);
        await backupPluginsOnly(id, s.path, (sid, log) => appendLog(sid, log));
      } catch (e) {
        appendLog(id, `[BACKUP] ⚠️ Plugin cloud save failed: ${e.message}`);
      }
    });
  } catch (e) {
    appendLog(id, `[SYSTEM] Modrinth installation failed: ${e.message}`);
    res.status(500).json({ error: e.message });
  }
});

// POST /api/servers/:id/modrinth/uninstall
app.post('/api/servers/:id/modrinth/uninstall', (req, res) => {
  const { id } = req.params;
  const { filename, projectType } = req.body;
  
  const servers = getServers();
  const s = servers.find((item) => item.id === id);
  if (!s) return res.status(404).json({ error: 'Server not found.' });

  try {
    let destDir = s.path;
    if (projectType === 'plugin') {
      destDir = path.join(s.path, 'plugins');
    } else if (projectType === 'mod') {
      destDir = path.join(s.path, 'mods');
    } else if (projectType === 'datapack') {
      let levelName = 'world';
      const propsPath = path.join(s.path, 'server.properties');
      if (fs.existsSync(propsPath)) {
        const text = fs.readFileSync(propsPath, 'utf8');
        const match = text.match(/level-name\s*=\s*(.+)/);
        if (match) levelName = match[1].trim();
      }
      destDir = path.join(s.path, levelName, 'datapacks');
    }

    const filePath = path.join(destDir, filename);
    if (fs.existsSync(filePath)) {
      fs.rmSync(filePath, { recursive: true, force: true });
      appendLog(id, `[SYSTEM] Uninstalled/Deleted ${filename} from ${projectType}s.`);
      res.json({ success: true });
    } else {
      res.status(404).json({ error: 'File not found.' });
    }
  } catch (e) {
    res.status(500).json({ error: e.message });
  }
});

// GET /api/velocity/settings
app.get('/api/velocity/settings', (req, res) => {
  const settingsPath = path.join(__dirname, 'backend', 'velocity-settings.json');
  if (fs.existsSync(settingsPath)) {
    try {
      const data = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
      res.json(data);
    } catch(e) {
      res.status(500).json({ error: e.message });
    }
  } else {
    res.json({ vpsIp: '', vpsPassword: '' });
  }
});

// POST /api/velocity/settings
app.post('/api/velocity/settings', (req, res) => {
  const { vpsIp, vpsPassword } = req.body;
  const settingsPath = path.join(__dirname, 'backend', 'velocity-settings.json');
  try {
    fs.writeFileSync(settingsPath, JSON.stringify({ vpsIp, vpsPassword }, null, 2));
    res.json({ success: true });
  } catch(e) {
    res.status(500).json({ error: e.message });
  }
});

// GET /api/velocity/network
app.get('/api/velocity/network', async (req, res) => {
  const settingsPath = path.join(__dirname, 'backend', 'velocity-settings.json');
  if (!fs.existsSync(settingsPath)) return res.json([]);
  try {
    const data = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
    if (!data.vpsIp || !data.vpsPassword) return res.json([]);
    const servers = await getVelocityServers(data.vpsIp, data.vpsPassword);
    res.json(servers);
  } catch(e) {
    res.status(500).json({ error: e.message });
  }
});

// POST /api/velocity/network/add
app.post('/api/velocity/network/add', async (req, res) => {
  const { name, address } = req.body;
  const settingsPath = path.join(__dirname, 'backend', 'velocity-settings.json');
  try {
    const data = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
    await addVelocityServer(data.vpsIp, data.vpsPassword, name, address);
    res.json({ success: true });
  } catch(e) {
    res.status(500).json({ error: e.message });
  }
});

// POST /api/velocity/network/remove
app.post('/api/velocity/network/remove', async (req, res) => {
  const { name } = req.body;
  const settingsPath = path.join(__dirname, 'backend', 'velocity-settings.json');
  try {
    const data = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
    await removeVelocityServer(data.vpsIp, data.vpsPassword, name);
    res.json({ success: true });
  } catch(e) {
    res.status(500).json({ error: e.message });
  }
});

// POST /api/spaces/deploy
app.post('/api/spaces/deploy', async (req, res) => {
  const { hfToken, sourceOwner, sourceRepo, newRepoName } = req.body;
  if (!hfToken || !sourceOwner || !sourceRepo || !newRepoName) {
    return res.status(400).json({ error: 'Missing required parameters.' });
  }
  
  const cleanRepoName = newRepoName.trim().replace(/[^a-zA-Z0-9-_\.\/]/g, '-').replace(/^-+|-+$/g, '');
  
  try {
    const result = await duplicateHFSpace(hfToken.trim(), sourceOwner.trim(), sourceRepo.trim(), cleanRepoName);
    res.json({ success: true, result });
  } catch (e) {
    res.status(500).json({ error: e.message });
  }
});

// GET /api/spaces/status
app.get('/api/spaces/status', async (req, res) => {
  const { hfToken, owner, repo } = req.query;
  if (!hfToken || !owner || !repo) {
    return res.status(400).json({ error: 'Missing required parameters.' });
  }
  
  try {
    const result = await checkSpaceStatus(hfToken, owner, repo);
    res.json({ success: true, result });
  } catch (e) {
    res.status(500).json({ error: e.message });
  }
});

// --- File Manager Endpoints ---

// List files in a directory
app.get('/api/servers/:id/files', async (req, res) => {
  const { id } = req.params;
  const subPath = req.query.path || '';
  const s = getServers().find(s => s.id === id);
  if (!s) return res.status(404).json({ error: 'Server not found' });
  
  try {
    const items = listFiles(s.path, subPath);
    res.json(items);
  } catch (e) {
    res.status(400).json({ error: e.message });
  }
});

// Read file content
app.get('/api/servers/:id/files/content', async (req, res) => {
  const { id } = req.params;
  const subPath = req.query.path;
  const s = getServers().find(s => s.id === id);
  if (!s) return res.status(404).json({ error: 'Server not found' });
  
  try {
    const content = readFileContent(s.path, subPath);
    res.send(content);
  } catch (e) {
    res.status(400).json({ error: e.message });
  }
});

// Save file content
app.post('/api/servers/:id/files/save', async (req, res) => {
  const { id } = req.params;
  const { path: subPath, content } = req.body;
  const s = getServers().find(s => s.id === id);
  if (!s) return res.status(404).json({ error: 'Server not found' });
  
  try {
    saveFileContent(s.path, subPath, content);
    res.json({ success: true });
  } catch (e) {
    res.status(400).json({ error: e.message });
  }
});

// Delete file or folder
app.post('/api/servers/:id/files/delete', async (req, res) => {
  const { id } = req.params;
  const { path: subPath } = req.body;
  const s = getServers().find(s => s.id === id);
  if (!s) return res.status(404).json({ error: 'Server not found' });
  
  try {
    deleteItem(s.path, subPath);
    res.json({ success: true });
  } catch (e) {
    res.status(400).json({ error: e.message });
  }
});

// Create folder
app.post('/api/servers/:id/files/mkdir', async (req, res) => {
  const { id } = req.params;
  const { path: subPath } = req.body;
  const s = getServers().find(s => s.id === id);
  if (!s) return res.status(404).json({ error: 'Server not found' });
  
  try {
    createFolder(s.path, subPath);
    res.json({ success: true });
  } catch (e) {
    res.status(400).json({ error: e.message });
  }
});

// Extract ZIP
app.post('/api/servers/:id/files/extract', async (req, res) => {
  const { id } = req.params;
  const { path: zipPath, destPath } = req.body;
  const s = getServers().find(s => s.id === id);
  if (!s) return res.status(404).json({ error: 'Server not found' });
  
  try {
    extractZip(s.path, zipPath, destPath);
    res.json({ success: true });
  } catch (e) {
    res.status(400).json({ error: e.message });
  }
});

// Upload File
app.post('/api/servers/:id/files/upload', upload.single('file'), async (req, res) => {
  const { id } = req.params;
  const subPath = req.body.path || '';
  const file = req.file;
  
  if (!file) return res.status(400).json({ error: 'No file uploaded' });
  
  const s = getServers().find(s => s.id === id);
  if (!s) return res.status(404).json({ error: 'Server not found' });
  
  try {
    const targetDir = path.join(s.path, subPath);
    if (!targetDir.startsWith(s.path)) throw new Error('Access denied');
    
    if (!fs.existsSync(targetDir)) {
      fs.mkdirSync(targetDir, { recursive: true });
    }
    
    const targetFilePath = path.join(targetDir, file.originalname);
    fs.copyFileSync(file.path, targetFilePath);
    fs.unlinkSync(file.path); // cleanup temp file
    
    res.json({ success: true, file: file.originalname });
  } catch (e) {
    if (fs.existsSync(file.path)) fs.unlinkSync(file.path);
    res.status(400).json({ error: e.message });
  }
});

// Upload World (Aternos Style)
app.post('/api/servers/:id/files/upload-world', upload.single('file'), async (req, res) => {
  const { id } = req.params;
  const file = req.file;
  if (!file) return res.status(400).json({ error: 'No file uploaded' });
  
  const s = getServers().find(s => s.id === id);
  if (!s) return res.status(404).json({ error: 'Server not found' });
  
  try {
    // 1. Delete old world folders
    const worldsToDelete = ['world', 'world_nether', 'world_the_end'];
    for (const w of worldsToDelete) {
      const wPath = path.join(s.path, w);
      if (fs.existsSync(wPath)) fs.rmSync(wPath, { recursive: true, force: true });
    }

    // 2. Copy zip to server path
    const targetZip = path.join(s.path, 'temp_world_upload.zip');
    fs.copyFileSync(file.path, targetZip);
    fs.unlinkSync(file.path);

    // 3. Extract and delete zip
    extractZip(s.path, 'temp_world_upload.zip', '');
    fs.unlinkSync(targetZip);
    
    // 4. If there is no 'world' folder, but a custom folder got extracted containing level.dat, rename it to 'world'
    if (!fs.existsSync(path.join(s.path, 'world'))) {
       const items = fs.readdirSync(s.path);
       for (const item of items) {
          const itemPath = path.join(s.path, item);
          if (fs.statSync(itemPath).isDirectory() && fs.existsSync(path.join(itemPath, 'level.dat'))) {
             fs.renameSync(itemPath, path.join(s.path, 'world'));
             break;
          }
       }
    }

    res.json({ success: true });
  } catch (e) {
    if (fs.existsSync(file.path)) fs.unlinkSync(file.path);
    res.status(400).json({ error: e.message });
  }
});

// Upload Plugin
app.post('/api/servers/:id/files/upload-plugin', upload.single('file'), async (req, res) => {
  const { id } = req.params;
  const file = req.file;
  if (!file) return res.status(400).json({ error: 'No file uploaded' });
  
  const s = getServers().find(s => s.id === id);
  if (!s) return res.status(404).json({ error: 'Server not found' });
  
  try {
    const pluginsDir = path.join(s.path, 'plugins');
    if (!fs.existsSync(pluginsDir)) fs.mkdirSync(pluginsDir, { recursive: true });
    
    const targetFilePath = path.join(pluginsDir, file.originalname);
    fs.copyFileSync(file.path, targetFilePath);
    fs.unlinkSync(file.path);
    
    res.json({ success: true, file: file.originalname });

    // ── Instantly backup after manual upload so plugins survive container restart ──
    setImmediate(async () => {
      try {
        appendLog(id, `[BACKUP] 💾 Saving plugins to cloud...`);
        await backupPluginsOnly(id, s.path, (sid, log) => appendLog(sid, log));
      } catch (e) {
        appendLog(id, `[BACKUP] ⚠️ Plugin cloud save failed: ${e.message}`);
      }
    });
  } catch (e) {
    if (fs.existsSync(file.path)) fs.unlinkSync(file.path);
    res.status(400).json({ error: e.message });
  }
});

  // --- WebSocket Gateway Connection Handler ---
wss.on('connection', async (ws, req) => {
  try {
    const parsedUrl = new URL(req.url, 'http://localhost');
    const token = parsedUrl.searchParams.get('token');
    
    // Use the same deterministic token logic as HTTP routes
    const config = await getAuthConfig();
    if (!token || !config || !config.passwordHash) {
      ws.close(4001, 'Unauthorized');
      return;
    }
    const expectedToken = generateStableToken(config.passwordHash, config.salt);
    if (token !== expectedToken) {
      ws.close(4001, 'Unauthorized');
      return;
    }
  } catch (e) {
    ws.close(4000, 'Invalid Request');
    return;
  }

  // Client messages
  ws.on('message', (messageText) => {
    try {
      const msg = JSON.parse(messageText);
      
      if (msg.type === 'subscribe') {
        const serverId = msg.serverId;
        subscriptions.set(ws, serverId);
        
        // Push backlog history
        const history = logHistory.get(serverId) || [];
        ws.send(JSON.stringify({ type: 'backlog', data: history }));
        
        // Push current status and players
        const isRunning = processManager.isRunning(serverId);
        const procInfo = processManager.processes.get(serverId);
        
        ws.send(JSON.stringify({
          type: 'status',
          data: isRunning ? procInfo.status : 'offline'
        }));
        
        ws.send(JSON.stringify({
          type: 'players',
          data: isRunning ? Array.from(procInfo.players) : []
        }));
      }
      
      if (msg.type === 'command') {
        const serverId = subscriptions.get(ws);
        if (serverId && msg.data) {
          // Minecraft console commands should not have a leading slash
          let cmd = msg.data.trim();
          if (cmd.startsWith('/')) {
            cmd = cmd.substring(1);
          }
          processManager.sendCommand(serverId, cmd);
        }
      }
    } catch (e) {
      console.error('WS parsing error:', e);
    }
  });

  ws.on('close', () => {
    subscriptions.delete(ws);
  });
});

// Serve compiled build assets if built, or direct homepage route
app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', (req, res) => {
  if (fs.existsSync(path.join(__dirname, 'dist', 'index.html'))) {
    res.sendFile(path.join(__dirname, 'dist', 'index.html'));
  } else {
    res.send('Vite Dev Server is running. Visit port 3000 to access the page.');
  }
});

// Start server after initial Firestore sync
async function start() {
  await syncFromFirestore();
  await autoRecoverServers();
  server.listen(PORT, '0.0.0.0', () => {
    console.log(`Minecraft Hoster Backend API listening on http://0.0.0.0:${PORT}`);
    console.log(`WebSocket server is running on ws://0.0.0.0:${PORT}`);
  });
}
start();