-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
444 lines (368 loc) · 15.9 KB
/
Program.cs
File metadata and controls
444 lines (368 loc) · 15.9 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
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Linq;
namespace FolderStateConsole
{
class Program
{
private const string version = "2.2";
private static volatile bool _running = false;
private static long _totalFiles = 0;
private static long _copiedFiles = 0;
private static long _totalBytes = 0;
private static long _copiedBytes = 0;
private static string _currentFile = "";
private static string _phase = "Idle";
private static long _scannedFiles = 0;
private static long _scannedBytes = 0;
private static string _currentScanDir = "";
private static readonly object _lock = new();
private static int _displayStartRow = 0;
private const int DisplayRows = 8;
static async Task<int> Main(string[] args)
{
Console.Title = $"RDKN - Backup Tool v{version} | © 2026 Redknack Interactive";
PrintBanner();
bool autoYes = args.Any(a =>
a.Equals("-y", StringComparison.OrdinalIgnoreCase) ||
a.Equals("--yes", StringComparison.OrdinalIgnoreCase));
string? targetArg = args.FirstOrDefault(a => !a.StartsWith("-", StringComparison.Ordinal));
string targetPath = string.IsNullOrWhiteSpace(targetArg)
? Directory.GetCurrentDirectory()
: targetArg;
try
{
if (!Directory.Exists(targetPath))
{
WriteColor($"Error: Directory not found: {targetPath}", ConsoleColor.Red);
return 1;
}
Directory.SetCurrentDirectory(targetPath);
_running = true;
_phase = "Scanning";
var displayTask = Task.Run(LiveDisplayLoop);
var config = await BuildConfigWithLiveScan();
_running = false;
await displayTask;
ShowConfiguration(config);
if (!autoYes)
{
WriteColor("\nStart backup? (Y/N): ", ConsoleColor.Yellow, newline: false);
var key = Console.ReadKey(intercept: true).Key;
Console.WriteLine();
if (key != ConsoleKey.Y)
{
WriteColor("Backup cancelled.", ConsoleColor.Yellow);
return 0;
}
}
else
{
WriteColor("Auto-confirm enabled (-y). Starting backup...\n", ConsoleColor.Yellow);
}
await PerformBackup(config);
return 0;
}
catch (Exception ex)
{
WriteColor($"Fatal error: {ex}", ConsoleColor.Red);
return 1;
}
finally
{
Console.ForegroundColor = ConsoleColor.Gray;
if (!autoYes)
{
Console.WriteLine("\nPress any key to exit...");
Console.ResetColor();
Console.ReadKey(intercept: true);
}
}
}
private static void LiveDisplayLoop()
{
lock (_lock) _displayStartRow = Console.CursorTop;
for (int i = 0; i < DisplayRows; i++) Console.WriteLine();
var startTime = DateTime.Now;
var lastUpdate = DateTime.MinValue;
while (_running)
{
if (DateTime.Now - lastUpdate < TimeSpan.FromMilliseconds(150))
{
Thread.Sleep(50);
continue;
}
lastUpdate = DateTime.Now;
var elapsed = DateTime.Now - startTime;
lock (_lock)
{
Console.SetCursorPosition(0, _displayStartRow);
if (_phase == "Scanning")
DrawScanFrame(elapsed);
else
DrawBackupFrame(elapsed);
}
}
Console.SetCursorPosition(0, _displayStartRow + DisplayRows);
}
private static void DrawScanFrame(TimeSpan elapsed)
{
ClearLine(); Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine($" {SpinChar(elapsed)} Scanning directory... [{elapsed:mm\\:ss}]");
ClearLine(); Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($" Files found : {_scannedFiles:N0}");
ClearLine(); Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($" Size so far : {FormatBytes(_scannedBytes)}");
ClearLine(); Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine($" Current : {TruncateLeft(_currentScanDir, 60)}");
for (int i = 4; i < DisplayRows; i++) ClearLine();
Console.ResetColor();
}
private static void DrawBackupFrame(TimeSpan elapsed)
{
int percent = _totalFiles > 0
? (int)Math.Min(100, (_copiedFiles * 100) / _totalFiles)
: 0;
ClearLine(); Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write(" Progress: ");
DrawBar(percent);
Console.WriteLine();
ClearLine(); Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($" Files : {_copiedFiles:N0} / {_totalFiles:N0} ({percent}%)");
ClearLine(); Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($" Data : {FormatBytes(_copiedBytes),10} / {FormatBytes(_totalBytes)}");
ClearLine(); Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine($" Elapsed : {elapsed:mm\\:ss}");
if (percent > 2 && elapsed.TotalSeconds > 0)
{
double speed = _copiedBytes / elapsed.TotalSeconds;
var eta = TimeSpan.FromSeconds(
elapsed.TotalSeconds * (100 - percent) / Math.Max(1, percent));
ClearLine(); Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.WriteLine($" Speed : {FormatBytes((long)speed)}/s ETA: {eta:mm\\:ss}");
}
else
{
ClearLine(); Console.ForegroundColor = ConsoleColor.DarkGray;
Console.WriteLine(" Speed : Calculating...");
}
ClearLine();
Console.WriteLine();
ClearLine(); Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine($" {_currentFile}");
Console.ResetColor();
}
private static async Task<BackupConfig> BuildConfigWithLiveScan()
{
var config = new BackupConfig();
var dirInfo = new DirectoryInfo(Directory.GetCurrentDirectory());
config.ProjectName = dirInfo.Name;
config.ProjectPath = dirInfo.FullName;
config.ParentPath = dirInfo.Parent?.FullName ?? dirInfo.FullName;
config.BackupFolderName = $"{config.ProjectName}_BACKUP_{DateTime.Now:yyyy-MM-dd_HH-mm-ss}";
config.BackupPath = Path.Combine(config.ParentPath, config.BackupFolderName);
await Task.Run(() =>
{
try { WalkDirectory(dirInfo); }
catch { }
});
lock (_lock)
{
config.TotalFiles = _scannedFiles;
config.TotalSize = _scannedBytes;
}
return config;
}
private static void WalkDirectory(DirectoryInfo dir)
{
lock (_lock) _currentScanDir = dir.FullName;
try
{
foreach (var file in dir.EnumerateFiles())
lock (_lock) { _scannedFiles++; _scannedBytes += file.Length; }
foreach (var sub in dir.EnumerateDirectories())
WalkDirectory(sub);
}
catch { }
}
private static async Task PerformBackup(BackupConfig config)
{
Console.Clear();
PrintBanner();
var stopwatch = Stopwatch.StartNew();
_running = true;
_phase = "Backup";
_totalFiles = config.TotalFiles;
_totalBytes = config.TotalSize;
_copiedFiles = 0;
_copiedBytes = 0;
_currentFile = "";
var displayTask = Task.Run(LiveDisplayLoop);
try
{
Directory.CreateDirectory(config.BackupPath);
await RunRobocopy(config);
stopwatch.Stop();
_running = false;
await displayTask;
ShowSuccessMessage(stopwatch.Elapsed, config);
}
catch (Exception ex)
{
_running = false;
WriteColor($"\nBackup error: {ex.Message}", ConsoleColor.Red);
}
}
private static async Task RunRobocopy(BackupConfig config)
{
var startInfo = new ProcessStartInfo
{
FileName = "robocopy",
Arguments = $"\"{config.ProjectPath}\" \"{config.BackupPath}\" " +
$"/MIR /XD \"{config.BackupPath}\" /XF \"*.bat\" /R:3 /W:1 /BYTES /NP /MT:1",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
using var process = Process.Start(startInfo)
?? throw new Exception("Failed to start Robocopy.");
_ = Task.Run(() => ParseRobocopyOutput(process));
await process.WaitForExitAsync();
_running = false;
if (process.ExitCode > 7)
throw new Exception($"Robocopy exited with code {process.ExitCode}");
}
private static void ParseRobocopyOutput(Process process)
{
while (!process.StandardOutput.EndOfStream)
{
var line = process.StandardOutput.ReadLine();
if (string.IsNullOrWhiteSpace(line)) continue;
bool isCopy = line.Contains("New File") || line.Contains("Newer")
|| line.Contains("Neuer") || line.Contains("Neue Datei");
if (!isCopy) continue;
var parts = line.Split('\t', StringSplitOptions.RemoveEmptyEntries);
string fileName = parts.Length > 0 ? Path.GetFileName(parts.Last().Trim()) : "";
long fileBytes = 0;
foreach (var part in parts)
{
var clean = part.Trim().Replace(",", "").Replace(".", "");
if (long.TryParse(clean, out long b)) { fileBytes = b; break; }
}
lock (_lock)
{
_copiedFiles++;
_copiedBytes += fileBytes;
_currentFile = fileName;
}
}
}
private static void PrintBanner()
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("===============================================================");
Console.WriteLine(" Backup Tool v" + version);
Console.WriteLine("===============================================================");
Console.ResetColor();
Console.WriteLine();
}
private static void ShowConfiguration(BackupConfig config)
{
Console.Clear();
PrintBanner();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("============ BACKUP CONFIGURATION ============");
Console.ResetColor();
Console.WriteLine();
void Row(string label, string value, ConsoleColor col)
{
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write($" {label,-15}");
Console.ForegroundColor = col;
Console.WriteLine(value);
Console.ResetColor();
}
Row("Project:", config.ProjectName, ConsoleColor.Yellow);
Row("Source:", TruncateLeft(config.ProjectPath, 50), ConsoleColor.White);
Row("Destination:", TruncateLeft(config.BackupPath, 50), ConsoleColor.Green);
Row("Files:", config.TotalFiles.ToString("N0"), ConsoleColor.Blue);
Row("Size:", FormatBytes(config.TotalSize), ConsoleColor.Cyan);
Row("Timestamp:", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ConsoleColor.Magenta);
try
{
var drive = new DriveInfo(Path.GetPathRoot(config.BackupPath)!);
Row("Free Space:", FormatBytes(drive.AvailableFreeSpace), ConsoleColor.DarkGreen);
}
catch { Row("Free Space:", "Unknown", ConsoleColor.Red); }
}
private static void ShowSuccessMessage(TimeSpan elapsed, BackupConfig config)
{
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("========= BACKUP COMPLETED SUCCESSFULLY =========");
Console.ResetColor();
Console.WriteLine();
Console.WriteLine($" Duration: {elapsed:mm\\:ss}");
Console.WriteLine($" Files copied: {_copiedFiles:N0}");
Console.WriteLine($" Data copied: {FormatBytes(_copiedBytes)}");
Console.WriteLine($" Destination: {config.BackupPath}");
Console.WriteLine($" Finished at: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
}
private static void DrawBar(int pct)
{
const int width = 46;
int filled = pct * width / 100;
Console.Write("[");
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(new string('█', filled));
Console.ForegroundColor = ConsoleColor.DarkGray;
Console.Write(new string('░', width - filled));
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write($"] {pct,3}%");
Console.ResetColor();
}
private static void ClearLine()
{
int top = Console.CursorTop;
Console.SetCursorPosition(0, top);
Console.Write(new string(' ', Console.WindowWidth - 1));
Console.SetCursorPosition(0, top);
}
private static string SpinChar(TimeSpan t)
{
string[] frames = { "⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏" };
return frames[(int)(t.TotalMilliseconds / 100) % frames.Length];
}
private static string FormatBytes(long bytes)
{
if (bytes == 0) return "0 B";
string[] sizes = { "B", "KB", "MB", "GB", "TB" };
double len = bytes; int order = 0;
while (len >= 1024 && order < sizes.Length - 1) { len /= 1024; order++; }
return $"{len:0.##} {sizes[order]}";
}
private static string TruncateLeft(string s, int max) =>
s.Length <= max ? s : "…" + s[^(max - 1)..];
private static void WriteColor(string msg, ConsoleColor col, bool newline = true)
{
Console.ForegroundColor = col;
if (newline) Console.WriteLine(msg);
else Console.Write(msg);
Console.ResetColor();
}
}
public class BackupConfig
{
public string ProjectName { get; set; } = "";
public string ProjectPath { get; set; } = "";
public string ParentPath { get; set; } = "";
public string BackupFolderName { get; set; } = "";
public string BackupPath { get; set; } = "";
public long TotalFiles { get; set; }
public long TotalSize { get; set; }
}
}