-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvpsmc.cpp
More file actions
1409 lines (1245 loc) · 57.2 KB
/
vpsmc.cpp
File metadata and controls
1409 lines (1245 loc) · 57.2 KB
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
/*
vpsmc - Virtual Private Server Master Control
This program reads server information from a 'servers.json' file
and displays it in a clean, scrollable, tabular format using the
ncurses library. It provides a terminal-based dashboard for a quick
overview of a list of servers.
Version: v0.213
Compilation Instruction (using the Makefile):
make vpsmc
*/
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <ncursesw/ncurses.h>
#include <thread>
#include <mutex>
#include <iomanip>
#include <chrono>
#include <cstring>
#include <wordexp.h>
#include <sys/stat.h>
#include <algorithm>
#include <atomic>
#include <tuple>
#include <cstdlib> // For setenv
#include <limits> // For std::numeric_limits
#include <fstream>
#include "vpsmc_lib.h" // Include the shared library header
// --- Enums and Globals ---
enum class SortKey { ID, NICKNAME, CANONICAL_NAME, IP_ADDRESS, OS, COMPANY, PURPOSE, COST, CPU, LOAD, MEM, SWAP, DISK, DISK2, DISK3, UPTIME, UPDATES, REBOOT };
SortKey current_sort_key = SortKey::ID;
bool sort_ascending = true;
std::atomic<bool> data_changed = true;
std::atomic<int> running_threads;
Config config; // Global config object
std::mutex server_mutex;
// --- UI Layout Constants ---
const int HEADER_HEIGHT = 5;
const int LIST_START_Y = HEADER_HEIGHT;
const int PANE_MIN_HEIGHT = 15;
const int SUMMARY_HEIGHT = 3;
// --- Column Layout Definitions (Single Source of Truth) ---
struct ColumnSpec {
const char* title;
const char* underline;
int start_pos;
const char* unit;
int unit_pos;
int arrow_pos;
SortKey key;
};
const std::vector<ColumnSpec> COLUMNS = {
{"ID", "---", 1, "", 0, 4, SortKey::ID},
{"NICKNAME", "----------", 5, "", 0, 14, SortKey::NICKNAME},
{"CANONICAL NAME", "---------------------", 16, "", 0, 31, SortKey::CANONICAL_NAME},
{"IP ADDRESS", "---------------", 38, "", 0, 49, SortKey::IP_ADDRESS},
{"OS", "----------", 54, "", 0, 57, SortKey::OS},
{"CO", "--", 65, "", 0, 68, SortKey::COMPANY},
{"PURPOSE", "----------------------", 69, "", 0, 77, SortKey::PURPOSE},
{"COST", "------", 92, "", 0, 97, SortKey::COST},
{"CPU", "---", 99, "", 0, 103, SortKey::CPU},
{"LOAD", "----", 103, "%", 106, 108, SortKey::LOAD},
{"MEM", "------", 108, "GiB", 108, 112, SortKey::MEM},
{"SWAP", "-----", 115, "GiB", 115, 119, SortKey::SWAP},
{"DSK1", "----", 121, "", 0, 125, SortKey::DISK},
{"DSK2", "----", 126, "", 0, 130, SortKey::DISK2},
{"DSK3", "----", 131, "", 0, 135, SortKey::DISK3},
{"UPTIME", "---------------", 136, "Yr Mo Dy Hr Mn", 136, 152, SortKey::UPTIME},
{"UPDTS", "-------", 153, "", 0, 159, SortKey::UPDATES},
{"REBOOT", "------", 161, "", 0, 168, SortKey::REBOOT}
};
const int NUM_COLUMNS = 18;
// --- Forward Declarations ---
void redraw_dynamic_content(std::vector<Server>& servers, size_t start_row, size_t selected_row, bool draw_header = false);
void draw_static_header(int max_x);
void draw_server_list(const std::vector<Server>& servers, size_t start_row, size_t selected_row, int max_x);
void draw_details_pane(const Server& server, int max_x);
void draw_summary(const std::vector<Server>& servers, int max_y, int max_x);
bool confirm_delete_popup(const std::string& nick, std::string& reason_out);
bool get_string_input(WINDOW* win, int y, int x, char* buffer, int size);
void draw_footer(int max_y, int max_x, bool is_loading, size_t displayed, size_t total);
void update_sort_indicator();
bool edit_server(Server& server, bool is_adding = false);
void sort_servers(std::vector<Server>& servers, SortKey key, bool ascending);
void launch_all_dynamic_data_threads(Server& server);
void show_error_popup(const std::string& message);
// --- Helper Functions ---
std::string format_uptime(double total_seconds) {
if (total_seconds < 0) {
if (total_seconds == -1.0) return " Fetching...";
return " ";
}
long long seconds = static_cast<long long>(total_seconds);
if (seconds < 60) return " < 1 min";
const long long SEC_PER_MIN = 60, SEC_PER_HOUR = 3600, SEC_PER_DAY = 86400,
SEC_PER_MONTH = 2629746, SEC_PER_YEAR = 31556952;
long long years = seconds / SEC_PER_YEAR; seconds %= SEC_PER_YEAR;
long long months = seconds / SEC_PER_MONTH; seconds %= SEC_PER_MONTH;
long long days = seconds / SEC_PER_DAY; seconds %= SEC_PER_HOUR;
long long hours = seconds / SEC_PER_HOUR; seconds %= SEC_PER_HOUR;
long long minutes = seconds / SEC_PER_MIN;
char yr_s[4], mo_s[4], dy_s[4], hr_s[4], mn_s[4];
snprintf(yr_s, sizeof(yr_s), "%s", (years > 0 ? std::to_string(years).c_str() : ""));
snprintf(mo_s, sizeof(mo_s), "%s", (months > 0 ? std::to_string(months).c_str() : ""));
snprintf(dy_s, sizeof(dy_s), "%s", (days > 0 ? std::to_string(days).c_str() : ""));
snprintf(hr_s, sizeof(hr_s), "%s", (hours > 0 ? std::to_string(hours).c_str() : ""));
snprintf(mn_s, sizeof(mn_s), "%s", (minutes > 0 ? std::to_string(minutes).c_str() : ""));
char final_buffer[100];
snprintf(final_buffer, sizeof(final_buffer), "%3s%3s%3s%3s%3s", yr_s, mo_s, dy_s, hr_s, mn_s);
return std::string(final_buffer);
}
// --- Drawing Sub-routines ---
void draw_static_header(int max_x) {
attron(A_BOLD | COLOR_PAIR(1));
// Row 0: top frame border with embedded title
move(0, 0);
addstr("┌");
for (int x = 1; x < max_x - 1; ++x) addstr("─");
mvaddstr(0, max_x - 1, "┐");
const char* title_buf = "VPS Master Control";
int title_x = (max_x - (int)strlen(title_buf) - 2) / 2;
mvprintw(0, title_x, " %s ", title_buf);
// Rows 1-4: │ borders with interior cleared
for (int y = 1; y < HEADER_HEIGHT; ++y) {
mvaddstr(y, 0, "│");
move(y, 1);
for (int x = 1; x < max_x - 1; ++x) addch(' ');
mvaddstr(y, max_x - 1, "│");
}
for(const auto& col : COLUMNS) {
int title_len = strlen(col.title);
int underline_len = strlen(col.underline);
int title_pos = col.start_pos;
// Right-align specific columns
if (col.key == SortKey::COST || col.key == SortKey::CPU || col.key == SortKey::LOAD || col.key == SortKey::MEM || col.key == SortKey::SWAP) {
title_pos = col.start_pos + underline_len - title_len;
}
mvprintw(2, title_pos, "%s", col.title);
mvprintw(3, col.start_pos, "%s", col.underline);
if (strlen(col.unit) > 0) {
mvprintw(4, col.unit_pos, "%s", col.unit);
}
}
attroff(A_BOLD | COLOR_PAIR(1));
}
void update_sort_indicator() {
attron(A_BOLD | COLOR_PAIR(1));
const char* arrow = sort_ascending ? "▲" : "▼";
int key_index = static_cast<int>(current_sort_key);
int x_pos = COLUMNS[key_index].arrow_pos;
mvprintw(2, x_pos, "%s", arrow);
attroff(A_BOLD | COLOR_PAIR(1));
}
void draw_server_list(const std::vector<Server>& servers, size_t start_row, size_t selected_row, int max_x) {
int max_y;
getmaxyx(stdscr, max_y, max_x);
const int SUMMARY_START_Y = max_y - PANE_MIN_HEIGHT - 1 - SUMMARY_HEIGHT;
const int list_height = SUMMARY_START_Y - LIST_START_Y;
for (int i = 0; i < list_height; ++i) {
int y = LIST_START_Y + i;
size_t server_idx = start_row + i;
bool is_even_row = (i % 2 != 0);
int base_color = is_even_row ? 6 : 5;
int disk_green_pair = is_even_row ? 17 : 16;
int disk_white_pair = is_even_row ? 34 : 33;
int disk_magenta_pair = is_even_row ? 36 : 35;
int disk_red_pair = is_even_row ? 21 : 20;
int update_pair = is_even_row ? 23 : 22;
int reboot_pair = is_even_row ? 25 : 24;
// Frame vertical borders for every row
attron(A_BOLD | COLOR_PAIR(1));
mvaddstr(y, 0, "│");
mvaddstr(y, max_x - 1, "│");
attroff(A_BOLD | COLOR_PAIR(1));
if(server_idx < servers.size()) {
const auto& s = servers[server_idx];
int current_row_color = (server_idx == selected_row) ? 3 : base_color;
attron(COLOR_PAIR(current_row_color));
for (int j = 1; j < max_x - 1; ++j) { mvaddch(y, j, ' '); }
mvprintw(y, 1, "%-3d", s.id);
mvprintw(y, 5, "%-10.10s", s.nick.c_str());
mvprintw(y, 16, "%-21.21s", s.canonical_name.c_str());
mvprintw(y, 38, "%-15s", s.network.ipv4.c_str());
std::string os_str = s.os.name.empty()
? "?"
: s.os.name.substr(0, 2) + " " + s.os.version;
mvprintw(y, 54, "%-10.10s", os_str.c_str());
mvprintw(y, 65, "%-2s", s.hpa.c_str());
mvprintw(y, 69, "%-22.22s", s.purpose.c_str());
if (s.monthly_cost_cents > 0)
mvprintw(y, 92, "%6.2f", (s.monthly_cost_cents / 100.0));
else
mvprintw(y, 92, " ?");
if (s.specs.cpu_cores > 0)
mvprintw(y, 99, "%3d", s.specs.cpu_cores);
else
mvprintw(y, 99, " ?");
if (s.cpu_load_percent >= 0) {
mvprintw(y, 103, "%4.1f", s.cpu_load_percent);
}
mvprintw(y, 108, "%6.3f", s.specs.memory_gb);
mvprintw(y, 115, "%5.1f", s.specs.swap_gb);
auto draw_disk_col = [&](int col, double pct) {
if (pct < 0.0) return;
std::stringstream ds;
ds << std::fixed << std::setprecision(0) << pct << "%";
std::string str = ds.str();
int color = 0;
if (pct >= 95.0) color = disk_red_pair;
else if (pct >= 80.0) color = disk_magenta_pair;
else if (pct >= 70.0) color = disk_white_pair;
else if (pct >= 0.0) color = disk_green_pair;
if (color > 0) {
attron(COLOR_PAIR(color));
mvprintw(y, col, "%4s", str.c_str());
attron(COLOR_PAIR(current_row_color));
}
};
draw_disk_col(121, s.specs.disk_used_percent);
draw_disk_col(126, s.specs.disk2_used_percent);
draw_disk_col(131, s.specs.disk3_used_percent);
mvprintw(y, 136, "%-15s", format_uptime(s.uptime_seconds).c_str());
if (s.updates.count > 0) {
attron(COLOR_PAIR(update_pair));
mvprintw(y, 153, "(%d)", s.updates.count);
attron(COLOR_PAIR(current_row_color));
}
if (s.reboot_required) {
attron(COLOR_PAIR(reboot_pair));
mvprintw(y, 161, "RBT");
attron(COLOR_PAIR(current_row_color));
}
}
attroff(COLOR_PAIR(base_color));
}
}
void draw_details_pane(const Server& server, int max_x) {
int max_y;
getmaxyx(stdscr, max_y, max_x);
const int PANE_START_Y = max_y - PANE_MIN_HEIGHT - 1;
const int PANE_END_Y = max_y - 2;
// Disk sub-section box geometry (right 1/3)
const int box_x = 2 * max_x / 3; // left border column of box
const int box_rx = max_x - 1; // right border column of box
// Inner width (between the two border chars)
const int inner_w = box_rx - box_x - 1;
// Column widths inside the box: label + device + mount + pct
const int label_w = 4;
const int pct_w = 4;
const int gap = 2; // spaces between each field
const int flex = inner_w - label_w - pct_w - gap * 3 - 2; // 2 = leading space + trailing space
const int dev_w = std::max(8, flex / 2);
const int mnt_w = std::max(5, flex - dev_w);
// ── Title row (section separator) ────────────────────────────────────────
attron(A_BOLD | COLOR_PAIR(1));
mvprintw(PANE_START_Y, 0, "├── DETAILS ");
move(PANE_START_Y, 12);
for (int i = 12; i < max_x - 1; ++i) addstr("─");
mvaddstr(PANE_START_Y, max_x - 1, "┤");
attroff(A_BOLD | COLOR_PAIR(1));
// ── Clear content rows with frame borders ────────────────────────────────
for (int y = PANE_START_Y + 1; y <= PANE_END_Y; ++y) {
attron(A_BOLD | COLOR_PAIR(1));
mvaddstr(y, 0, "│");
mvaddstr(y, max_x - 1, "│");
attroff(A_BOLD | COLOR_PAIR(1));
for (int x = 1; x < max_x - 1; ++x)
mvaddch(y, x, ' ');
}
// ── Left section: server info ─────────────────────────────────────────────
char cost_buf[64];
if (server.monthly_cost_cents > 0)
snprintf(cost_buf, sizeof(cost_buf), "%.2f %s/mo",
server.monthly_cost_cents / 100.0, server.cost_currency.c_str());
else
snprintf(cost_buf, sizeof(cost_buf), "?");
mvprintw(PANE_START_Y + 2, 2, " Nickname : %-20s", server.nick.c_str());
mvprintw(PANE_START_Y + 2, 46, " Canonical Name: %s", server.canonical_name.c_str());
mvprintw(PANE_START_Y + 3, 2, " IP Address : %-20s", server.network.ipv4.c_str());
mvprintw(PANE_START_Y + 3, 46, " Purpose : %s", server.purpose.c_str());
mvprintw(PANE_START_Y + 4, 2, " OS : %s %s", server.os.name.c_str(), server.os.version.c_str());
mvprintw(PANE_START_Y + 4, 46, " Reboot Req : %s", server.reboot_required ? "Yes" : "No");
mvprintw(PANE_START_Y + 5, 2, " ISP : %-20s", server.provider.c_str());
mvprintw(PANE_START_Y + 5, 46, " HPA Code : %s", server.hpa.c_str());
mvprintw(PANE_START_Y + 6, 2, " Cost : %s", cost_buf);
mvprintw(PANE_START_Y + 7, 2, " CPU Cores : %d", server.specs.cpu_cores);
mvprintw(PANE_START_Y + 7, 46, " Memory : %.3f GB", server.specs.memory_gb);
mvprintw(PANE_START_Y + 8, 2, " Swap : %.3f GB", server.specs.swap_gb);
// ── DISK SPACE sub-section (right 1/3, no box) ───────────────────────────
const int DISK_HDR = PANE_START_Y + 2;
attron(A_BOLD | COLOR_PAIR(1));
mvprintw(DISK_HDR, box_x + 1, "DISK SPACE");
attroff(A_BOLD | COLOR_PAIR(1));
// ── Disk rows: label | pct | device | mount ───────────────────────────────
struct DiskSlot {
const char* label;
double pct;
const std::string* device;
const std::string* mount;
};
const DiskSlot slots[3] = {
{ "DSK1", server.specs.disk_used_percent, &server.specs.disk1_device, &server.specs.disk1_mount },
{ "DSK2", server.specs.disk2_used_percent, &server.specs.disk2_device, &server.specs.disk2_mount },
{ "DSK3", server.specs.disk3_used_percent, &server.specs.disk3_device, &server.specs.disk3_mount },
};
for (int d = 0; d < 3; ++d) {
const int row = DISK_HDR + 1 + d;
const auto& slot = slots[d];
int cx = box_x + 1;
// Label (bold)
attron(A_BOLD);
mvprintw(row, cx, " %-*s", label_w, slot.label);
attroff(A_BOLD);
cx += 1 + label_w + gap;
if (slot.pct < 0.0 || slot.device->empty()) {
mvprintw(row, cx, "%-*s", dev_w, "(none)");
continue;
}
// Percentage: color-coded, immediately after label
int dcolor = 0;
if (slot.pct >= 95.0) dcolor = 15;
else if (slot.pct >= 80.0) dcolor = 13;
else if (slot.pct >= 70.0) dcolor = 14;
else if (slot.pct >= 0.0) dcolor = 12;
char pct_str[8];
snprintf(pct_str, sizeof(pct_str), "%3.0f%%", slot.pct);
if (dcolor) attron(COLOR_PAIR(dcolor) | A_BOLD);
mvprintw(row, cx, "%-*s", pct_w, pct_str);
if (dcolor) attroff(COLOR_PAIR(dcolor) | A_BOLD);
cx += pct_w + gap;
// Device name (truncated)
mvprintw(row, cx, "%-*.*s", dev_w, dev_w, slot.device->c_str());
cx += dev_w + gap;
// Mount point (truncated)
mvprintw(row, cx, "%-*.*s", mnt_w, mnt_w, slot.mount->c_str());
}
}
void draw_summary(const std::vector<Server>& servers, int max_y, int max_x) {
const int y0 = max_y - PANE_MIN_HEIGHT - 1 - SUMMARY_HEIGHT; // separator row
const int y1 = y0 + 1; // data row
const int y2 = y0 + 2; // blank spacer
// Sum only servers with a known cost
long total_cents = 0;
bool any_cost_known = false;
for (const auto& s : servers) {
if (s.monthly_cost_cents > 0) {
total_cents += s.monthly_cost_cents;
any_cost_known = true;
}
}
attron(A_BOLD | COLOR_PAIR(1));
// y0: section separator
mvprintw(y0, 0, "├── COST TOTAL ");
move(y0, 15);
for (int x = 15; x < max_x - 1; ++x) addstr("─");
mvaddstr(y0, max_x - 1, "┤");
// y1, y2: clear interior with frame borders
for (int y = y1; y <= y2; ++y) {
mvaddstr(y, 0, "│");
move(y, 1);
for (int x = 1; x < max_x - 1; ++x) addch(' ');
mvaddstr(y, max_x - 1, "│");
}
// Total value right-aligned at column 97 (matching individual cost cells: %6.2f at col 92)
if (any_cost_known)
mvprintw(y1, 92, "%6.2f /mo", total_cents / 100.0);
else
mvprintw(y1, 92, " ? /mo");
attroff(A_BOLD | COLOR_PAIR(1));
}
void draw_footer(int max_y, int max_x, bool is_loading, size_t displayed, size_t total) {
attron(A_BOLD | COLOR_PAIR(1));
// Bottom frame border: └ ... ┘
move(max_y - 1, 0);
addstr("└");
for (int i = 1; i < max_x - 1; ++i) addch(' ');
mvaddstr(max_y - 1, max_x - 1, "┘");
const char* help_text = " ENTER: Edit | A/+: Add | d: Delete | s: Sort | r/R: Check | ARROWS: Navigate | q: Quit";
const char* version_text = "vpsmc v0.213";
char count_buf[20];
snprintf(count_buf, sizeof(count_buf), "[%zu/%zu]", displayed, total);
mvprintw(max_y - 1, 1, "%s", help_text);
int version_pos = max_x - strlen(version_text) - 6;
mvprintw(max_y - 1, version_pos, "%s", version_text);
int count_pos = version_pos - strlen(count_buf) - 2;
mvprintw(max_y - 1, count_pos, "%s", count_buf);
if (is_loading) {
attron(COLOR_PAIR(11)); // Orange foreground
mvaddwstr(max_y - 1, max_x - 3, L"🟠");
attroff(COLOR_PAIR(11));
} else {
attron(COLOR_PAIR(12)); // Green foreground
mvaddwstr(max_y - 1, max_x - 3, L"✅");
attroff(COLOR_PAIR(12));
}
// Redraw closing corner in case emoji rendering advanced past it
attron(A_BOLD | COLOR_PAIR(1));
mvaddstr(max_y - 1, max_x - 1, "┘");
attroff(A_BOLD | COLOR_PAIR(1));
refresh();
}
// --- MAIN DRAW FUNCTION ---
// draw_header: only needed on startup, sort change, or terminal resize
void redraw_dynamic_content(std::vector<Server>& servers, size_t start_row, size_t selected_row,
bool draw_header) {
int max_x;
getmaxyx(stdscr, max_x, max_x);
for(auto& s : servers) {
if (s.uptime_seconds > 0 && s.specs.cpu_cores > 0) {
double total_time = s.uptime_seconds * s.specs.cpu_cores;
double busy_time = total_time - s.idle_seconds;
s.cpu_load_percent = (busy_time / total_time) * 100.0;
} else {
s.cpu_load_percent = -1.0;
}
}
if (draw_header) {
draw_static_header(max_x);
update_sort_indicator();
}
int max_y;
getmaxyx(stdscr, max_y, max_x);
draw_server_list(servers, start_row, selected_row, max_x);
draw_summary(servers, max_y, max_x);
// Details pane is NOT drawn here — the main loop draws it only when the
// input queue is empty so rapid navigation never triggers a details redraw.
refresh();
}
void show_error_popup(const std::string& message) {
int max_y, max_x;
getmaxyx(stdscr, max_y, max_x);
int height = 5, width = message.length() + 6;
int start_y = (max_y - height) / 2;
int start_x = (max_x - width) / 2;
WINDOW* win = newwin(height, width, start_y, start_x);
wbkgd(win, COLOR_PAIR(2)); // Use error color scheme
box(win, 0, 0);
mvwprintw(win, 2, 3, "%s", message.c_str());
wrefresh(win);
timeout(-1);
getch();
timeout(200);
delwin(win);
}
// Returns true if confirmed; sets reason_out to the entered reason (empty = none given).
// ESC or empty+Enter without 'y' confirmation cancels.
bool confirm_delete_popup(const std::string& nick, std::string& reason_out) {
int max_y, max_x;
getmaxyx(stdscr, max_y, max_x);
const int width = 56, height = 10;
int start_y = (max_y - height) / 2;
int start_x = (max_x - width) / 2;
WINDOW* win = newwin(height, width, start_y, start_x);
keypad(win, TRUE);
wbkgd(win, COLOR_PAIR(2));
box(win, 0, 0);
wattron(win, A_BOLD | COLOR_PAIR(2));
mvwprintw(win, 1, (width - 14) / 2, "DELETE SERVER");
wattroff(win, A_BOLD | COLOR_PAIR(2));
mvwprintw(win, 3, 3, "Remove '%s' from the list?", nick.c_str());
mvwprintw(win, 5, 3, "Reason: ");
mvwprintw(win, 8, 3, "ENTER to confirm, ESC to cancel");
wrefresh(win);
char reason_buf[80] = {};
bool confirmed = get_string_input(win, 5, 11, reason_buf, sizeof(reason_buf));
delwin(win);
touchwin(stdscr);
if (confirmed) reason_out = reason_buf;
return confirmed;
}
void show_sort_popup(SortKey& key, bool& ascending) {
int max_y, max_x;
getmaxyx(stdscr, max_y, max_x);
int height = 18, width = 54;
int start_y = (max_y - height) / 2;
int start_x = (max_x - width) / 2;
WINDOW* win = newwin(height, width, start_y, start_x);
wbkgd(win, COLOR_PAIR(1));
box(win, 0, 0);
wattron(win, A_BOLD | COLOR_PAIR(1));
mvwprintw(win, 1, (width - 17) / 2, "Select Sort Key");
wattroff(win, A_BOLD | COLOR_PAIR(1));
const std::vector<std::tuple<const char*, char, SortKey>> sort_options = {
{"ID", 'I', SortKey::ID}, {"Nickname", 'N', SortKey::NICKNAME},
{"Canonical Name", 'L', SortKey::CANONICAL_NAME}, {"IP Address", 'A', SortKey::IP_ADDRESS},
{"OS", 'O', SortKey::OS}, {"Company/HPC", 'G', SortKey::COMPANY},
{"Purpose", 'M', SortKey::PURPOSE}, {"Cost", 'C', SortKey::COST},
{"CPU Cores", 'U', SortKey::CPU}, {"Processor Load", 'P', SortKey::LOAD},
{"Memory", 'R', SortKey::MEM}, {"Swap", 'W', SortKey::SWAP},
{"Disk", 'D', SortKey::DISK}, {"Uptime", 'T', SortKey::UPTIME},
{"Updates", 'S', SortKey::UPDATES}, {"Reboot", 'B', SortKey::REBOOT}
};
for(size_t i=0; i < 8; ++i) { // Loop for 8 rows
int row_color = (i % 2 != 0) ? 9 : 10;
wattron(win, COLOR_PAIR(row_color));
int row = 3 + i;
mvwprintw(win, row, 1, "%*s", width - 2, "");
if (i < sort_options.size()) {
char left_buf[30];
snprintf(left_buf, sizeof(left_buf), "%2ld. %s (%c)", i+1, std::get<0>(sort_options[i]), std::get<1>(sort_options[i]));
mvwprintw(win, row, 2, "%-25s", left_buf);
}
if (i + 8 < sort_options.size()) {
char right_buf[30];
snprintf(right_buf, sizeof(right_buf), "%2ld. %s (%c)", i+9, std::get<0>(sort_options[i+8]), std::get<1>(sort_options[i+8]));
mvwprintw(win, row, 28, "%-25s", right_buf);
}
wattroff(win, COLOR_PAIR(row_color));
}
wattron(win, A_BOLD | COLOR_PAIR(1));
mvwprintw(win, height - 2, 2, "Press letter or number & ENTER, or q to close.");
wattroff(win, A_BOLD | COLOR_PAIR(1));
wrefresh(win);
int ch;
std::string num_buffer;
while(true) {
ch = wgetch(win);
if (isdigit(ch)) {
if (num_buffer.length() < 2) {
num_buffer += ch;
wattron(win, A_BOLD | COLOR_PAIR(1));
mvwprintw(win, height - 2, 48, "[%-2s]", num_buffer.c_str());
wattroff(win, A_BOLD | COLOR_PAIR(1));
wrefresh(win);
}
continue;
}
SortKey new_key = key;
bool key_found = false;
if (ch == '\n' || ch == KEY_ENTER) {
if (!num_buffer.empty()) {
int num = std::stoi(num_buffer);
if (num >= 1 && (size_t)num <= sort_options.size()) {
new_key = std::get<2>(sort_options[num - 1]);
key_found = true;
}
}
} else if (isalpha(ch)) {
ch = toupper(ch);
for(const auto& opt : sort_options) {
if(std::get<1>(opt) == ch) {
new_key = std::get<2>(opt);
key_found = true;
break;
}
}
} else if (ch == 'q' || ch == 's') {
delwin(win); touchwin(stdscr); refresh(); return;
}
if (key_found) {
if (new_key == key) {
ascending = !ascending;
} else {
key = new_key;
switch (new_key) {
case SortKey::COST:
case SortKey::CPU:
case SortKey::LOAD:
case SortKey::MEM:
case SortKey::SWAP:
case SortKey::DISK:
case SortKey::DISK2:
case SortKey::DISK3:
case SortKey::UPTIME:
case SortKey::UPDATES:
ascending = false; // Default to descending for these
break;
default:
ascending = true; // Default to ascending for others
break;
}
}
}
delwin(win); touchwin(stdscr); refresh();
return;
}
}
// --- First-Run Wizard (shown when servers.json is missing or empty) ---
struct SshConfigHost {
std::string nick;
std::string hostname;
std::string user;
int port = 22;
};
static std::vector<SshConfigHost> parse_ssh_config() {
std::vector<SshConfigHost> hosts;
std::ifstream file(expand_path("~/.ssh/config"));
if (!file.is_open()) return hosts;
SshConfigHost current;
bool in_host = false;
std::string line;
while (std::getline(file, line)) {
size_t start = line.find_first_not_of(" \t");
if (start == std::string::npos || line[start] == '#') continue;
line = line.substr(start);
size_t sp = line.find_first_of(" \t=");
std::string key = (sp == std::string::npos) ? line : line.substr(0, sp);
std::string val;
if (sp != std::string::npos) {
size_t vs = line.find_first_not_of(" \t=", sp);
if (vs != std::string::npos) {
val = line.substr(vs);
size_t ve = val.find_last_not_of(" \t\r");
if (ve != std::string::npos) val = val.substr(0, ve + 1);
}
}
std::string lkey = key;
std::transform(lkey.begin(), lkey.end(), lkey.begin(), ::tolower);
if (lkey == "host") {
// Save previous host if it was a plain alias (no wildcards or spaces)
if (in_host && current.nick.find_first_of("*? ") == std::string::npos)
hosts.push_back(current);
current = SshConfigHost();
current.nick = val;
in_host = true;
} else if (in_host) {
if (lkey == "hostname") current.hostname = val;
else if (lkey == "user") current.user = val;
else if (lkey == "port") { try { current.port = std::stoi(val); } catch (...) {} }
}
}
if (in_host && current.nick.find_first_of("*? ") == std::string::npos)
hosts.push_back(current);
return hosts;
}
// Scrollable checklist of SSH config hosts. Returns indices of selected entries.
static std::vector<int> show_ssh_host_selector(const std::vector<SshConfigHost>& hosts) {
int max_y, max_x;
getmaxyx(stdscr, max_y, max_x);
const int list_max = (int)hosts.size();
const int h = std::min(list_max + 7, max_y - 4);
const int w = std::min(70, max_x - 4);
const int list_h = h - 6;
WINDOW* win = newwin(h, w, (max_y - h) / 2, (max_x - w) / 2);
keypad(win, TRUE);
wbkgd(win, COLOR_PAIR(1));
std::vector<bool> selected(hosts.size(), false);
int cursor = 0, scroll_off = 0;
while (true) {
box(win, 0, 0);
wattron(win, A_BOLD | COLOR_PAIR(1));
const char* title = "Import from ~/.ssh/config";
mvwprintw(win, 1, (w - (int)strlen(title)) / 2, "%s", title);
wattroff(win, A_BOLD | COLOR_PAIR(1));
mvwprintw(win, 2, 2, "SPACE:toggle j/k:move a:all ENTER:import ESC:cancel");
for (int i = 0; i < list_h; ++i) {
int idx = scroll_off + i;
int row = 4 + i;
mvwprintw(win, row, 1, "%*s", w - 2, "");
if (idx >= list_max) continue;
bool cur = (idx == cursor);
if (cur) wattron(win, COLOR_PAIR(3) | A_BOLD);
const char* hname = hosts[idx].hostname.empty()
? hosts[idx].nick.c_str()
: hosts[idx].hostname.c_str();
mvwprintw(win, row, 2, "[%c] %-16.16s %-28.28s",
selected[idx] ? 'x' : ' ', hosts[idx].nick.c_str(), hname);
if (cur) wattroff(win, COLOR_PAIR(3) | A_BOLD);
}
int sel_count = (int)std::count(selected.begin(), selected.end(), true);
mvwprintw(win, h - 2, 2, "%d of %d selected ", sel_count, list_max);
wrefresh(win);
int ch = wgetch(win);
switch (ch) {
case KEY_DOWN: case 'j':
if (cursor < list_max - 1) { ++cursor; if (cursor >= scroll_off + list_h) ++scroll_off; }
break;
case KEY_UP: case 'k':
if (cursor > 0) { --cursor; if (cursor < scroll_off) --scroll_off; }
break;
case ' ':
selected[cursor] = !selected[cursor];
break;
case 'a': case 'A': {
bool all = std::all_of(selected.begin(), selected.end(), [](bool b){ return b; });
std::fill(selected.begin(), selected.end(), !all);
break;
}
case '\n': case KEY_ENTER: {
std::vector<int> result;
for (int i = 0; i < list_max; ++i)
if (selected[i]) result.push_back(i);
delwin(win); touchwin(stdscr); refresh();
return result;
}
case 27: case 'q': case 'Q':
delwin(win); touchwin(stdscr); refresh();
return {};
}
}
}
// Welcome dialog loop. Returns servers to use; empty means the user chose to quit.
static std::vector<Server> run_first_run_wizard(const Config& config) {
std::vector<Server> servers;
int max_y, max_x;
while (servers.empty()) {
getmaxyx(stdscr, max_y, max_x);
const int h = 14, w = 62;
WINDOW* win = newwin(h, w, (max_y - h) / 2, (max_x - w) / 2);
wbkgd(win, COLOR_PAIR(1));
box(win, 0, 0);
wattron(win, A_BOLD | COLOR_PAIR(1));
const char* title = "VPS Master Control";
mvwprintw(win, 1, (w - (int)strlen(title)) / 2, "%s", title);
wattroff(win, A_BOLD | COLOR_PAIR(1));
mvwprintw(win, 3, 3, "No server data found at:");
mvwprintw(win, 4, 5, "%-52.52s", config.servers_json_path.c_str());
mvwprintw(win, 6, 3, "How would you like to get started?");
wattron(win, A_BOLD | COLOR_PAIR(1));
mvwprintw(win, 8, 5, "i");
mvwprintw(win, 9, 5, "a");
mvwprintw(win, 11, 5, "q");
wattroff(win, A_BOLD | COLOR_PAIR(1));
mvwprintw(win, 8, 8, "Import hosts from ~/.ssh/config");
mvwprintw(win, 9, 8, "Add a server manually");
mvwprintw(win, 11, 8, "Quit");
wrefresh(win);
int ch = wgetch(win);
delwin(win);
touchwin(stdscr);
refresh();
if (ch == 'q' || ch == 'Q' || ch == 27) return servers; // empty = quit
if (ch == 'i' || ch == 'I') {
auto ssh_hosts = parse_ssh_config();
if (ssh_hosts.empty()) {
show_error_popup("No Host entries found in ~/.ssh/config.");
} else {
auto idxs = show_ssh_host_selector(ssh_hosts);
int next_id = 1;
for (int idx : idxs) {
const auto& h = ssh_hosts[idx];
Server s;
s.id = next_id++;
s.nick = h.nick;
// If HostName looks like an IPv4 address, store it as the IP.
// Otherwise use it as the canonical name (fetch_canonical_name will
// verify/overwrite it from the server itself on first connect).
bool is_ip = !h.hostname.empty()
&& h.hostname.find_first_not_of("0123456789.") == std::string::npos
&& h.hostname.find('.') != std::string::npos;
if (is_ip)
s.network.ipv4 = h.hostname;
else
s.canonical_name = h.hostname.empty() ? h.nick : h.hostname;
s.status = "unknown";
s.reboot_required = false;
s.uptime_seconds = -1.0;
s.idle_seconds = -1.0;
s.cpu_load_percent = -1.0;
s.is_checking = false;
s.specs.disk_used_percent = -1.0;
s.specs.disk2_used_percent = -1.0;
s.specs.disk3_used_percent = -1.0;
servers.push_back(s);
}
}
} else if (ch == 'a' || ch == 'A') {
Server s;
s.id = 1;
s.uptime_seconds = -1.0;
s.idle_seconds = -1.0;
s.cpu_load_percent = -1.0;
s.is_checking = false;
s.specs.disk_used_percent = -1.0;
s.specs.disk2_used_percent = -1.0;
s.specs.disk3_used_percent = -1.0;
if (edit_server(s, true)) servers.push_back(s);
// If cancelled, loop back to welcome screen
}
}
return servers;
}
int main(int argc, char* argv[]) {
setenv("TERM", "xterm-256color", 1);
setlocale(LC_ALL, "en_US.UTF-8");
if (!load_config(config)) {
return 1;
}
if (argc > 1 && (strcmp(argv[1], "-v") == 0 || strcmp(argv[1], "--version") == 0)) {
std::cout << "vpsmc v0.213" << std::endl;
return 0;
}
mkdir(config.log_directory_path.c_str(), 0755);
initscr();
cbreak();
noecho();
keypad(stdscr, TRUE);
set_escdelay(25); // reduce ESC recognition lag (default is 1000ms)
curs_set(0);
if (has_colors()) {
start_color();
init_pair(1, 255, 24); init_pair(2, 255, 196); init_pair(3, 16, 226);
init_pair(4, 255, 16); init_pair(5, 0, 81); init_pair(6, 0, 51);
init_pair(7, 16, 208); init_pair(8, 0, 244);
init_pair(9, 0, 230); init_pair(10, 0, 251);
use_default_colors();
init_pair(11, 208, -1); // Orange foreground
init_pair(12, 46, -1); // Green foreground (disk ok)
init_pair(13, 198, -1); // Magenta (disk high)
init_pair(14, 255, -1); // Bright white (disk moderate)
init_pair(15, 196, -1); // Red (disk critical)
init_pair(16, 22, 81); // Dark Green on light
init_pair(17, 22, 51); // Dark Green on dark
init_pair(20, 196, 81); // Red on light
init_pair(21, 196, 51); // Red on dark
init_pair(22, 16, 81); // Yellow on light
init_pair(23, 16, 51); // Yellow on dark
init_pair(24, 255, 196); // White on Red
init_pair(25, 255, 196);
init_pair(33, 255, 81); // White on light
init_pair(34, 255, 51); // White on dark
init_pair(35, 198, 81); // Magenta on light
init_pair(36, 198, 51); // Magenta on dark
}
int max_y, max_x;
getmaxyx(stdscr, max_y, max_x);
draw_static_header(max_x);
update_sort_indicator();
draw_footer(max_y, max_x, true, 0, 0);
auto servers = loadServers(config.servers_json_path);
if (servers.empty()) {
servers = run_first_run_wizard(config);
if (servers.empty()) {
endwin();
return 0;
}
save_servers(config.servers_json_path, servers);
}
sort_servers(servers, current_sort_key, sort_ascending);
redraw_dynamic_content(servers, 0, 0);
for (auto& server : servers) {
launch_all_dynamic_data_threads(server);
}
size_t start_row = 0;
size_t selected_row = 0;
bool header_dirty = true; // draw header on first frame
// Key handler lambda — updates state, returns false on quit
const int display_rows = max_y - PANE_MIN_HEIGHT - 1 - SUMMARY_HEIGHT - LIST_START_Y;
auto handle_key = [&](int ch) -> bool {
data_changed = true;
switch (ch) {
case 'j': case KEY_DOWN:
if (selected_row < servers.size() - 1) {
selected_row++;
if (selected_row >= start_row + display_rows)
start_row = selected_row - display_rows + 1;
}
break;
case 'k': case KEY_UP:
if (selected_row > 0) {
selected_row--;
if (selected_row < start_row)
start_row = selected_row;
}
break;
case KEY_ENTER: case '\n':
if(edit_server(servers[selected_row]))
save_servers(config.servers_json_path, servers);
touchwin(stdscr);
header_dirty = true;
break;
case 'd': case KEY_DC:
if (!servers.empty() && selected_row < servers.size()) {
std::string reason;
const Server& del_srv = servers[selected_row];
if (confirm_delete_popup(del_srv.nick, reason)) {
std::string log_msg = "DELETED server '" + del_srv.nick +
"' (" + del_srv.canonical_name + ", " + del_srv.network.ipv4 + ")";
if (!reason.empty()) log_msg += " -- Reason: " + reason;