sysmaint 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. sysmaint/__init__.py +17 -0
  2. sysmaint/__main__.py +6 -0
  3. sysmaint/cli.py +637 -0
  4. sysmaint/config.py +229 -0
  5. sysmaint/gui/__init__.py +5 -0
  6. sysmaint/gui/app.py +193 -0
  7. sysmaint/gui/components/__init__.py +13 -0
  8. sysmaint/gui/components/cards.py +239 -0
  9. sysmaint/gui/components/console.py +61 -0
  10. sysmaint/gui/components/dialogs.py +79 -0
  11. sysmaint/gui/theme.py +52 -0
  12. sysmaint/gui/views/__init__.py +25 -0
  13. sysmaint/gui/views/backup.py +167 -0
  14. sysmaint/gui/views/cleaner.py +227 -0
  15. sysmaint/gui/views/dashboard.py +252 -0
  16. sysmaint/gui/views/diagnostics.py +243 -0
  17. sysmaint/gui/views/integrity.py +158 -0
  18. sysmaint/gui/views/malware.py +293 -0
  19. sysmaint/gui/views/network.py +171 -0
  20. sysmaint/gui/views/security.py +118 -0
  21. sysmaint/gui/views/settings.py +211 -0
  22. sysmaint/gui/views/startup.py +133 -0
  23. sysmaint/logging_setup.py +62 -0
  24. sysmaint/modules/__init__.py +41 -0
  25. sysmaint/modules/backup.py +106 -0
  26. sysmaint/modules/cleaner.py +249 -0
  27. sysmaint/modules/disk.py +160 -0
  28. sysmaint/modules/drivers.py +89 -0
  29. sysmaint/modules/integrity.py +148 -0
  30. sysmaint/modules/malware.py +412 -0
  31. sysmaint/modules/memory.py +105 -0
  32. sysmaint/modules/network.py +167 -0
  33. sysmaint/modules/optimizer.py +186 -0
  34. sysmaint/modules/recovery.py +353 -0
  35. sysmaint/modules/report.py +232 -0
  36. sysmaint/modules/restore.py +123 -0
  37. sysmaint/modules/scheduler.py +137 -0
  38. sysmaint/modules/security.py +88 -0
  39. sysmaint/modules/services.py +171 -0
  40. sysmaint/modules/startup.py +95 -0
  41. sysmaint/modules/sysinfo.py +112 -0
  42. sysmaint/service/__init__.py +5 -0
  43. sysmaint/service/server.py +210 -0
  44. sysmaint/tui/__init__.py +5 -0
  45. sysmaint/tui/app.py +830 -0
  46. sysmaint/tui/modals.py +201 -0
  47. sysmaint/tui/themes.py +97 -0
  48. sysmaint/utils/__init__.py +39 -0
  49. sysmaint/utils/common.py +255 -0
  50. sysmaint/utils/escalate.py +93 -0
  51. sysmaint/utils/linux.py +240 -0
  52. sysmaint/utils/parsers.py +171 -0
  53. sysmaint/utils/windows.py +308 -0
  54. sysmaint-0.1.0.dist-info/METADATA +307 -0
  55. sysmaint-0.1.0.dist-info/RECORD +57 -0
  56. sysmaint-0.1.0.dist-info/WHEEL +4 -0
  57. sysmaint-0.1.0.dist-info/entry_points.txt +5 -0
sysmaint/__init__.py ADDED
@@ -0,0 +1,17 @@
1
+ """SysMaint - Cross-Platform System Maintenance, Security & Recovery Microservice."""
2
+
3
+ __version__ = "0.1.0"
4
+ __codename__ = "Sentinel Microservice"
5
+ __brand__ = "Kennny7 Microservices"
6
+ __author__ = "Kennny7"
7
+
8
+ from .config import SysMaintConfig, load_config, save_config
9
+
10
+ __all__ = [
11
+ "SysMaintConfig",
12
+ "__brand__",
13
+ "__codename__",
14
+ "__version__",
15
+ "load_config",
16
+ "save_config",
17
+ ]
sysmaint/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Entry point for `python -m sysmaint`."""
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
sysmaint/cli.py ADDED
@@ -0,0 +1,637 @@
1
+ # sysmaint/cli.py
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ try:
11
+ from rich.console import Console
12
+ from rich.panel import Panel
13
+ console = Console()
14
+ except ImportError:
15
+ console = None
16
+
17
+ from . import __brand__, __codename__, __version__
18
+ from .config import SysMaintConfig, load_config
19
+ from .logging_setup import setup_logging
20
+ from .modules import (
21
+ backup as backup_module,
22
+ )
23
+ from .modules import (
24
+ cleaner as cleaner_module,
25
+ )
26
+ from .modules import (
27
+ disk as disk_module,
28
+ )
29
+ from .modules import (
30
+ drivers as drivers_module,
31
+ )
32
+ from .modules import (
33
+ integrity as integrity_module,
34
+ )
35
+ from .modules import (
36
+ malware as malware_module,
37
+ )
38
+ from .modules import (
39
+ memory as memory_module,
40
+ )
41
+ from .modules import (
42
+ network as network_module,
43
+ )
44
+ from .modules import (
45
+ optimizer as optimizer_module,
46
+ )
47
+ from .modules import (
48
+ recovery as recovery_module,
49
+ )
50
+ from .modules import (
51
+ report as report_module,
52
+ )
53
+ from .modules import (
54
+ restore as restore_module,
55
+ )
56
+ from .modules import (
57
+ scheduler as scheduler_module,
58
+ )
59
+ from .modules import (
60
+ security as security_module,
61
+ )
62
+ from .modules import (
63
+ services as services_module,
64
+ )
65
+ from .modules import (
66
+ startup as startup_module,
67
+ )
68
+ from .modules import (
69
+ sysinfo as sysinfo_module,
70
+ )
71
+ from .utils.escalate import is_elevated, request_elevation
72
+
73
+
74
+ def build_parser() -> argparse.ArgumentParser:
75
+ """Create the argparse parser with all SysMaint subcommands."""
76
+ parser = argparse.ArgumentParser(
77
+ prog="sysmaint",
78
+ description=f"SysMaint v{__version__} ({__codename__}) - {__brand__}",
79
+ )
80
+ parser.add_argument(
81
+ "--version",
82
+ action="version",
83
+ version=f"SysMaint v{__version__} ({__codename__}) | {__brand__}",
84
+ )
85
+
86
+ # Global options
87
+ parser.add_argument(
88
+ "--config",
89
+ type=Path,
90
+ help="Path to config file (YAML or JSON)",
91
+ )
92
+ parser.add_argument(
93
+ "--log",
94
+ type=Path,
95
+ help="Log output to FILE",
96
+ )
97
+ parser.add_argument(
98
+ "--yes", "-y",
99
+ action="store_true",
100
+ help="Answer all prompts with 'yes'",
101
+ )
102
+ parser.add_argument(
103
+ "--offline",
104
+ action="store_true",
105
+ help="Disable online checks/scans",
106
+ )
107
+ parser.add_argument(
108
+ "--verbose", "-v",
109
+ action="store_true",
110
+ help="Verbose debug output",
111
+ )
112
+ parser.add_argument(
113
+ "--json",
114
+ action="store_true",
115
+ help="Output machine-readable JSON",
116
+ )
117
+ parser.add_argument(
118
+ "--html",
119
+ type=Path,
120
+ help="Export comprehensive HTML report to FILE",
121
+ )
122
+ parser.add_argument(
123
+ "--dry-run",
124
+ action="store_true",
125
+ help="Show what would be done without making changes",
126
+ )
127
+ parser.add_argument(
128
+ "--elevate",
129
+ action="store_true",
130
+ help="Request administrator / root privileges before executing",
131
+ )
132
+
133
+ subparsers = parser.add_subparsers(dest="command", required=False)
134
+
135
+ # tui
136
+ p_tui = subparsers.add_parser("tui", help="Launch interactive Terminal Client UI")
137
+ p_tui.add_argument("--server", help="Optional microservice URL (e.g. http://127.0.0.1:8765)")
138
+ p_tui.set_defaults(func=cmd_tui)
139
+
140
+ # serve
141
+ p_serve = subparsers.add_parser("serve", help="Run SysMaint as a local HTTP microservice")
142
+ p_serve.add_argument("--host", default="127.0.0.1", help="Bind host (default: 127.0.0.1)")
143
+ p_serve.add_argument("--port", type=int, default=8765, help="Bind port (default: 8765)")
144
+ p_serve.set_defaults(func=cmd_serve)
145
+
146
+ # gui
147
+ p_gui = subparsers.add_parser("gui", help="Launch modern graphical user interface")
148
+ p_gui.set_defaults(func=cmd_gui)
149
+
150
+ # smart-scan
151
+ p_smart = subparsers.add_parser("smart-scan", help="Run 1-Click Smart System Health Scan")
152
+ p_smart.set_defaults(func=cmd_smart_scan)
153
+
154
+ # optimize
155
+ p_opt = subparsers.add_parser("optimize", help="Run 1-Click Auto-Fix & System Optimization")
156
+ p_opt.set_defaults(func=cmd_optimize)
157
+
158
+ # clean
159
+ p_clean = subparsers.add_parser("clean", help="Clean junk, temporary files, and browser caches")
160
+ p_clean.add_argument("--temp", action="store_true", help="Clean temporary files")
161
+ p_clean.add_argument("--browser", action="store_true", help="Clean browser caches")
162
+ p_clean.add_argument("--logs", action="store_true", help="Clean system logs and crash dumps")
163
+ p_clean.add_argument("--package", action="store_true", help="Clean package manager caches")
164
+ p_clean.add_argument("--thumbnails", action="store_true", help="Clean thumbnail caches")
165
+ p_clean.add_argument("--all", action="store_true", help="Clean all junk categories")
166
+ p_clean.set_defaults(func=cmd_clean)
167
+
168
+ # info
169
+ p_info = subparsers.add_parser("info", help="Display hardware specs and operating system details")
170
+ p_info.set_defaults(func=cmd_info)
171
+
172
+ # diagnose
173
+ p_diag = subparsers.add_parser("diagnose", help="Run diagnostics (disk, memory, services, drivers)")
174
+ p_diag.add_argument("--disk", action="store_true", help="Check disk")
175
+ p_diag.add_argument("--memory", action="store_true", help="Check memory")
176
+ p_diag.add_argument("--services", action="store_true", help="Check services")
177
+ p_diag.add_argument("--drivers", action="store_true", help="Check drivers")
178
+ p_diag.add_argument("--all", action="store_true", help="Run all diagnostics")
179
+ p_diag.set_defaults(func=cmd_diagnose)
180
+
181
+ # scan
182
+ p_scan = subparsers.add_parser("scan", help="Perform malware and integrity scans")
183
+ p_scan.add_argument("--clamav", action="store_true", help="Run ClamAV scan")
184
+ p_scan.add_argument("--yara", action="store_true", help="Run YARA scan")
185
+ p_scan.add_argument("--virustotal", action="store_true", help="Run VirusTotal scan")
186
+ p_scan.add_argument("--integrity", action="store_true", help="Run system integrity check")
187
+ p_scan.add_argument("--target", type=Path, help="Specific file or folder to scan")
188
+ p_scan.add_argument("--all", action="store_true", help="Run all scans")
189
+ p_scan.set_defaults(func=cmd_scan)
190
+
191
+ # repair
192
+ p_repair = subparsers.add_parser("repair", help="Attempt repairs based on diagnostics")
193
+ p_repair.add_argument("--disk", action="store_true", help="Repair disk/filesystem")
194
+ p_repair.add_argument("--services", action="store_true", help="Repair services (start expected)")
195
+ p_repair.add_argument("--files", action="store_true", help="Repair system files (DISM/SFC)")
196
+ p_repair.add_argument("--network", action="store_true", help="Reset corrupted network stack")
197
+ p_repair.add_argument("--offline-source", help="Local WIM/ESD source for offline DISM repair")
198
+ p_repair.add_argument("--all", action="store_true", help="Run all repairs")
199
+ p_repair.set_defaults(func=cmd_repair)
200
+
201
+ # startup
202
+ p_startup = subparsers.add_parser("startup", help="Manage startup applications and autoruns")
203
+ p_startup.add_argument("action", nargs="?", default="list", choices=["list", "enable", "disable"])
204
+ p_startup.add_argument("name", nargs="?", help="Startup application name")
205
+ p_startup.set_defaults(func=cmd_startup)
206
+
207
+ # network
208
+ p_net = subparsers.add_parser("network", help="Network diagnostics, ping, DNS flush, and stack reset")
209
+ p_net.add_argument("action", nargs="?", default="status", choices=["status", "ping", "flush-dns", "ports", "reset"])
210
+ p_net.add_argument("--target", default="1.1.1.1", help="Target host to ping")
211
+ p_net.set_defaults(func=cmd_network)
212
+
213
+ # recovery
214
+ p_rec = subparsers.add_parser("recovery", help="Data recovery (Recycle Bin/Trash, VSS shadows, temp drafts, file carving)")
215
+ p_rec.add_argument("action", nargs="?", default="trash", choices=["trash", "restore", "shadows", "temp", "carve"])
216
+ p_rec.add_argument("--name", help="Deleted item name to restore from Trash/Recycle Bin")
217
+ p_rec.add_argument("--dest", type=Path, help="Destination directory for recovered files")
218
+ p_rec.add_argument("--source", type=Path, help="Source image/file for signature carving")
219
+ p_rec.add_argument("--types", nargs="+", help="File types to carve (pdf png jpg zip sqlite)")
220
+ p_rec.add_argument("--limit", type=int, default=50, help="Max items to list or carve")
221
+ p_rec.set_defaults(func=cmd_recovery)
222
+
223
+ # security
224
+ p_sec = subparsers.add_parser("security", help="Audit security posture (Antivirus, Firewall, Elevation)")
225
+ p_sec.set_defaults(func=cmd_security)
226
+
227
+ # backup
228
+ p_backup = subparsers.add_parser("backup", help="Create backups or restore points")
229
+ p_backup.add_argument("--snapshot", action="store_true", help="Create LVM/Btrfs snapshot")
230
+ p_backup.add_argument("--restore-point", action="store_true", help="Create Windows restore point")
231
+ p_backup.add_argument("--registry", action="store_true", help="Create Windows registry backup")
232
+ p_backup.set_defaults(func=cmd_backup)
233
+
234
+ # restore
235
+ p_restore = subparsers.add_parser("restore", help="Restore from a backup snapshot or restore point")
236
+ p_restore.add_argument("--list", action="store_true", help="List available backups and restore points")
237
+ p_restore.add_argument("--ui", action="store_true", help="Launch native system recovery UI")
238
+ p_restore.add_argument("--snapshot", metavar="NAME", help="Restore from snapshot NAME")
239
+ p_restore.add_argument("--restore-point", metavar="NAME", help="Restore from restore point NAME")
240
+ p_restore.set_defaults(func=cmd_restore)
241
+
242
+ # service
243
+ p_service = subparsers.add_parser("service", help="Manage system services")
244
+ p_service.add_argument("action", choices=["start", "stop", "restart", "status", "list"])
245
+ p_service.add_argument("service_name", nargs="?", help="Service identifier name")
246
+ p_service.set_defaults(func=cmd_service)
247
+
248
+ # schedule
249
+ p_sched = subparsers.add_parser("schedule", help="Manage recurring automated maintenance tasks")
250
+ p_sched.add_argument("action", choices=["status", "install", "remove"])
251
+ p_sched.add_argument("--interval", default="WEEKLY", choices=["DAILY", "WEEKLY", "MONTHLY"])
252
+ p_sched.add_argument("--time", default="02:00", help="Time to execute (HH:MM)")
253
+ p_sched.set_defaults(func=cmd_schedule)
254
+
255
+ # update-db
256
+ p_update = subparsers.add_parser("update-db", help="Update ClamAV signature database")
257
+ p_update.set_defaults(func=cmd_update_db)
258
+
259
+ # report
260
+ p_report = subparsers.add_parser("report", help="Generate full system health report")
261
+ p_report.set_defaults(func=cmd_report)
262
+
263
+ return parser
264
+
265
+
266
+ def _merge_config(args: argparse.Namespace) -> SysMaintConfig:
267
+ """Load config from file if provided, then apply CLI overrides."""
268
+ if getattr(args, "config", None):
269
+ config = load_config(args.config)
270
+ else:
271
+ config = load_config()
272
+
273
+ if getattr(args, "offline", False):
274
+ config.system.offline_mode = True
275
+ if getattr(args, "yes", False):
276
+ config.system.auto_yes = True
277
+ if getattr(args, "log", None):
278
+ config.logging.file = args.log
279
+
280
+ return config
281
+
282
+
283
+ # ---------------- Command Handlers ----------------
284
+
285
+
286
+ def cmd_tui(args: argparse.Namespace, config: SysMaintConfig) -> dict[str, Any]:
287
+ """Launch the interactive Terminal Client UI."""
288
+ from .tui.app import launch_tui
289
+ launch_tui(config=config, server_url=getattr(args, "server", None))
290
+ return {"status": "TUI Closed"}
291
+
292
+
293
+ def cmd_serve(args: argparse.Namespace, config: SysMaintConfig) -> dict[str, Any]:
294
+ """Run SysMaint as an HTTP microservice."""
295
+ from .service.server import run_server
296
+ if console:
297
+ console.print(
298
+ Panel.fit(
299
+ f"[bold cyan]SysMaint v{__version__} ({__codename__})[/bold cyan]\n"
300
+ f"Microservice listening on [green]http://{args.host}:{args.port}[/green]\n"
301
+ f"OpenAPI Docs: [underline]http://{args.host}:{args.port}/docs[/underline]\n"
302
+ f"Powered by [bold]{__brand__}[/bold]",
303
+ border_style="cyan",
304
+ )
305
+ )
306
+ run_server(host=args.host, port=args.port)
307
+ return {"status": "Microservice Stopped"}
308
+
309
+
310
+ def cmd_gui(args: argparse.Namespace, config: SysMaintConfig) -> dict[str, Any]:
311
+ """Launch the modern graphical user interface."""
312
+ from .gui.app import SysMaintApp
313
+ app = SysMaintApp(config=config)
314
+ app.mainloop()
315
+ return {"status": "GUI Closed"}
316
+
317
+
318
+ def cmd_smart_scan(args: argparse.Namespace, config: SysMaintConfig) -> dict[str, Any]:
319
+ """Run 1-Click Smart System Health Scan."""
320
+ return {"smart_scan": optimizer_module.run_smart_scan(config)}
321
+
322
+
323
+ def cmd_optimize(args: argparse.Namespace, config: SysMaintConfig) -> dict[str, Any]:
324
+ """Run 1-Click Auto-Fix & System Optimization."""
325
+ return {"optimizer": optimizer_module.run_auto_fix(config, create_restore=not args.dry_run)}
326
+
327
+
328
+ def cmd_clean(args: argparse.Namespace, config: SysMaintConfig) -> dict[str, Any]:
329
+ """Handler for `sysmaint clean`."""
330
+ cats = []
331
+ if args.all or not any([args.temp, args.browser, args.logs, args.package, args.thumbnails]):
332
+ cats = None
333
+ else:
334
+ if args.temp:
335
+ cats.extend(["user_temp", "system_temp"])
336
+ if args.browser:
337
+ cats.append("browser_cache")
338
+ if args.logs:
339
+ cats.append("system_logs")
340
+ if args.package:
341
+ cats.append("package_cache")
342
+ if args.thumbnails:
343
+ cats.append("thumbnails")
344
+
345
+ return {"cleaner": cleaner_module.clean_junk(categories=cats, dry_run=args.dry_run)}
346
+
347
+
348
+ def cmd_info(args: argparse.Namespace, config: SysMaintConfig) -> dict[str, Any]:
349
+ """Display hardware specs and operating system details."""
350
+ return {"sysinfo": sysinfo_module.get_system_specs()}
351
+
352
+
353
+ def cmd_diagnose(args: argparse.Namespace, config: SysMaintConfig) -> dict[str, Any]:
354
+ """Handler for `sysmaint diagnose`."""
355
+ results: dict[str, Any] = {}
356
+ run_all = args.all or not any([args.disk, args.memory, args.services, args.drivers])
357
+
358
+ if run_all or args.disk:
359
+ results["disk"] = disk_module.check_disk(repair=False)
360
+ if run_all or args.memory:
361
+ results["memory"] = memory_module.check_memory()
362
+ if run_all or args.services:
363
+ results["services"] = services_module.list_services()
364
+ if run_all or args.drivers:
365
+ results["drivers"] = drivers_module.check_drivers()
366
+
367
+ return results
368
+
369
+
370
+ def cmd_scan(args: argparse.Namespace, config: SysMaintConfig) -> dict[str, Any]:
371
+ """Handler for `sysmaint scan`."""
372
+ results: dict[str, Any] = {}
373
+ run_all = args.all or not any([args.clamav, args.yara, args.virustotal, args.integrity])
374
+
375
+ if run_all or args.integrity:
376
+ results["integrity"] = integrity_module.check_integrity(repair=False)
377
+
378
+ if run_all or args.clamav or args.yara or args.virustotal:
379
+ mal_cfg = config.malware
380
+ if not run_all:
381
+ mal_cfg = malware_module.MalwareConfig(
382
+ use_clamav=args.clamav,
383
+ use_yara=args.yara,
384
+ yara_rules_path=config.malware.yara_rules_path,
385
+ use_virustotal=args.virustotal,
386
+ vt_api_key=config.malware.vt_api_key,
387
+ )
388
+ results["malware"] = malware_module.scan(
389
+ mal_cfg,
390
+ target=args.target,
391
+ offline=config.system.offline_mode,
392
+ quick_scan=args.target is None,
393
+ )
394
+
395
+ return results
396
+
397
+
398
+ def cmd_repair(args: argparse.Namespace, config: SysMaintConfig) -> dict[str, Any]:
399
+ """Handler for `sysmaint repair`."""
400
+ results: dict[str, Any] = {}
401
+ run_all = args.all or not any([args.disk, args.services, args.files, args.network])
402
+
403
+ if args.dry_run:
404
+ results["dry_run"] = True
405
+
406
+ if run_all or args.disk:
407
+ if not args.dry_run:
408
+ results["disk"] = disk_module.check_disk(repair=True)
409
+ else:
410
+ results["disk"] = {"dry_run": "chkdsk /f or fsck -y"}
411
+
412
+ if run_all or args.services:
413
+ if not args.dry_run and config.services.enable:
414
+ results["services"] = services_module.ensure_expected_services(
415
+ config.services.expected_services
416
+ )
417
+ else:
418
+ results["services"] = {"dry_run": "ensure expected services"}
419
+
420
+ if run_all or args.files:
421
+ if not args.dry_run:
422
+ results["integrity"] = integrity_module.check_integrity(
423
+ repair=True,
424
+ offline_source=getattr(args, "offline_source", None),
425
+ )
426
+ else:
427
+ results["integrity"] = {"dry_run": "DISM /RestoreHealth and SFC /scannow"}
428
+
429
+ if run_all or args.network:
430
+ results["network"] = network_module.reset_network_stack(dry_run=args.dry_run)
431
+
432
+ return results
433
+
434
+
435
+ def cmd_startup(args: argparse.Namespace, config: SysMaintConfig) -> dict[str, Any]:
436
+ """Handler for `sysmaint startup`."""
437
+ if args.action == "list":
438
+ return {"startup_items": startup_module.list_startup_items()}
439
+ elif args.action in ("enable", "disable"):
440
+ if not args.name:
441
+ return {"error": f"Please specify the startup item name to {args.action}"}
442
+ return startup_module.toggle_startup_item(args.name, enable=(args.action == "enable"))
443
+ return {"startup_items": startup_module.list_startup_items()}
444
+
445
+
446
+ def cmd_network(args: argparse.Namespace, config: SysMaintConfig) -> dict[str, Any]:
447
+ """Handler for `sysmaint network`."""
448
+ if args.action == "status":
449
+ return {"interfaces": network_module.get_network_interfaces()}
450
+ elif args.action == "ping":
451
+ return {"ping": network_module.test_connectivity(args.target)}
452
+ elif args.action == "flush-dns":
453
+ return {"dns_flush": network_module.flush_dns()}
454
+ elif args.action == "ports":
455
+ return {"ports": network_module.get_listening_ports()}
456
+ elif args.action == "reset":
457
+ return {"network_reset": network_module.reset_network_stack(dry_run=args.dry_run)}
458
+ return {"interfaces": network_module.get_network_interfaces()}
459
+
460
+
461
+ def cmd_recovery(args: argparse.Namespace, config: SysMaintConfig) -> dict[str, Any]:
462
+ """Handler for `sysmaint recovery`."""
463
+ if args.action == "trash":
464
+ return {"trash": recovery_module.list_trash_items(limit=args.limit)}
465
+ elif args.action == "restore":
466
+ return {
467
+ "restore": recovery_module.restore_trash_item(
468
+ name=args.name or "",
469
+ destination=args.dest,
470
+ dry_run=args.dry_run,
471
+ )
472
+ }
473
+ elif args.action == "shadows":
474
+ return {"shadows": recovery_module.list_shadow_copies()}
475
+ elif args.action == "temp":
476
+ return {"temp_recovery": recovery_module.scan_recoverable_temp_files(limit=args.limit)}
477
+ elif args.action == "carve":
478
+ if not args.source or not args.dest:
479
+ return {"error": "Provide both --source <image_or_file> and --dest <output_dir> for carving."}
480
+ return {
481
+ "carve": recovery_module.carve_recoverable_files(
482
+ source_path=args.source,
483
+ output_dir=args.dest,
484
+ file_types=args.types,
485
+ max_files=args.limit,
486
+ dry_run=args.dry_run,
487
+ )
488
+ }
489
+ return {"trash": recovery_module.list_trash_items(limit=args.limit)}
490
+
491
+
492
+ def cmd_security(args: argparse.Namespace, config: SysMaintConfig) -> dict[str, Any]:
493
+ """Handler for `sysmaint security`."""
494
+ return {"security": security_module.audit_security_posture()}
495
+
496
+
497
+ def cmd_backup(args: argparse.Namespace, config: SysMaintConfig) -> dict[str, Any]:
498
+ """Handler for `sysmaint backup`."""
499
+ kind = "auto"
500
+ if args.snapshot:
501
+ kind = "snapshot"
502
+ elif args.restore_point:
503
+ kind = "restore-point"
504
+ elif args.registry:
505
+ kind = "registry"
506
+
507
+ if args.dry_run:
508
+ return {"dry_run": f"create backup of kind '{kind}'"}
509
+ return backup_module.create_backup(config, kind)
510
+
511
+
512
+ def cmd_restore(args: argparse.Namespace, config: SysMaintConfig) -> dict[str, Any]:
513
+ """Handler for `sysmaint restore`."""
514
+ if args.list:
515
+ return {"backups": restore_module.list_available_backups(config)}
516
+ if args.ui:
517
+ return restore_module.launch_system_recovery()
518
+ if args.snapshot:
519
+ return restore_module.restore_backup(config, args.snapshot, kind="snapshot")
520
+ if args.restore_point:
521
+ return restore_module.restore_backup(config, args.restore_point, kind="restore-point")
522
+ return {"error": "Use --list to view backups or specify --snapshot / --restore-point"}
523
+
524
+
525
+ def cmd_service(args: argparse.Namespace, config: SysMaintConfig) -> dict[str, Any]:
526
+ """Handler for `sysmaint service`."""
527
+ if args.action == "list":
528
+ return {"services": services_module.list_services()}
529
+ if not args.service_name:
530
+ return {"error": f"Please specify service_name for action '{args.action}'"}
531
+ if args.action == "status":
532
+ return {
533
+ "name": args.service_name,
534
+ "status": services_module.service_status(args.service_name),
535
+ }
536
+ return services_module.control_service(args.service_name, args.action)
537
+
538
+
539
+ def cmd_schedule(args: argparse.Namespace, config: SysMaintConfig) -> dict[str, Any]:
540
+ """Handler for `sysmaint schedule`."""
541
+ if args.action == "status":
542
+ return {"schedule": scheduler_module.get_schedule_status()}
543
+ elif args.action == "install":
544
+ return scheduler_module.install_schedule(interval=args.interval, time_str=args.time)
545
+ elif args.action == "remove":
546
+ return scheduler_module.remove_schedule()
547
+ return {"schedule": scheduler_module.get_schedule_status()}
548
+
549
+
550
+ def cmd_update_db(args: argparse.Namespace, config: SysMaintConfig) -> dict[str, Any]:
551
+ """Handler for `sysmaint update-db`."""
552
+ if args.dry_run:
553
+ return {"dry_run": "update malware database"}
554
+ return malware_module.update_malware_database()
555
+
556
+
557
+ def cmd_report(args: argparse.Namespace, config: SysMaintConfig) -> dict[str, Any]:
558
+ """Handler for `sysmaint report`."""
559
+ # Run full diagnostics, cleaner preview, and security audit
560
+ results: dict[str, Any] = {
561
+ "sysinfo": sysinfo_module.get_system_specs(),
562
+ "smart_scan": optimizer_module.run_smart_scan(config),
563
+ "security": security_module.audit_security_posture(),
564
+ "disk": disk_module.check_disk(repair=False),
565
+ "memory": memory_module.check_memory(),
566
+ }
567
+ return results
568
+
569
+
570
+ def main(argv: list[str] | None = None) -> None:
571
+ """Main entry point for SysMaint CLI."""
572
+ parser = build_parser()
573
+ args = parser.parse_args(argv)
574
+
575
+ # If no subcommand provided, default to TUI if interactive or show help
576
+ if not getattr(args, "command", None):
577
+ if len(sys.argv) == 1:
578
+ try:
579
+ cmd_tui(args, load_config())
580
+ return
581
+ except Exception:
582
+ parser.print_help()
583
+ return
584
+ parser.print_help()
585
+ return
586
+
587
+ # Elevate if explicitly requested
588
+ if getattr(args, "elevate", False) and not is_elevated():
589
+ request_elevation()
590
+
591
+ config = _merge_config(args)
592
+
593
+ logger = setup_logging(
594
+ level=config.logging.level,
595
+ log_file=config.logging.file,
596
+ verbose=args.verbose,
597
+ )
598
+
599
+ logger.info("SysMaint starting (command=%s)", args.command)
600
+
601
+ # Execute selected command
602
+ results = args.func(args, config)
603
+
604
+ # HTML Export if requested
605
+ if getattr(args, "html", None):
606
+ rep = report_module.build_report(results)
607
+ report_module.generate_html_report(rep, output_path=args.html)
608
+ if not args.json:
609
+ print(f"Exported HTML report to: {args.html}")
610
+
611
+ # Standard Output
612
+ report = report_module.build_report(results)
613
+ if args.json:
614
+ output = report_module.format_report(report, json_output=True)
615
+ print(output)
616
+ else:
617
+ output = report_module.format_report(report, json_output=False)
618
+ print(output)
619
+
620
+ # Determine exit code
621
+ exit_code = 1 if _contains_error(results) else 0
622
+ sys.exit(exit_code)
623
+
624
+
625
+ def _contains_error(data: Any) -> bool:
626
+ """Recursively check if a result dict contains an 'error' key."""
627
+ if isinstance(data, dict):
628
+ if "error" in data:
629
+ return True
630
+ return any(_contains_error(value) for value in data.values())
631
+ if isinstance(data, list):
632
+ return any(_contains_error(item) for item in data)
633
+ return False
634
+
635
+
636
+ if __name__ == "__main__":
637
+ main()