import argparse import json import os from pathlib import Path import sys from typing import List, Optional from linux_updater import __version__ from linux_updater.config import UpdaterConfig from linux_updater.core.detector import DistroDetector from linux_updater.core.health import HealthChecker from linux_updater.core.lock import InstanceLock from linux_updater.core.remediation import RemediationEngine from linux_updater.core.runner import CommandRunner from linux_updater.managers import get_manager from linux_updater.models import CheckStatus, DistroFamily def create_parser() -> argparse.ArgumentParser: common = argparse.ArgumentParser(add_help=False) common.add_argument( "-c", "--config", type=str, default=argparse.SUPPRESS, help="Path to JSON configuration file (default: /etc/linux-updater.json).", ) common.add_argument( "-y", "--yes", "--non-interactive", dest="non_interactive", action="store_true", default=argparse.SUPPRESS, help="Run without interactive confirmation prompts (ideal for cron and automation).", ) common.add_argument( "--dry-run", action="store_true", default=argparse.SUPPRESS, help="Simulate execution without modifying system state.", ) common.add_argument( "--no-remediation", action="store_true", default=argparse.SUPPRESS, help="Disable automatic remediation of failed pre-flight health checks.", ) common.add_argument( "--skip-preflight", action="store_true", default=argparse.SUPPRESS, help="Skip pre-flight health checks (not recommended).", ) common.add_argument( "--json", action="store_true", default=argparse.SUPPRESS, help="Output structured JSON results.", ) common.add_argument( "--reboot", dest="auto_reboot", action="store_true", default=argparse.SUPPRESS, help="Automatically reboot the system after a major release upgrade (or if reboot is required).", ) parser = argparse.ArgumentParser( prog="linux-updater", description="Unified, safe multi-distribution Linux system updater and health inspector.", formatter_class=argparse.RawDescriptionHelpFormatter, parents=[common], epilog=""" Examples: linux-updater health # Run pre-flight health diagnostic checks linux-updater check # Check for available updates without applying sudo linux-updater update # Update system packages interactively sudo linux-updater update -y # Non-interactive automated update sudo linux-updater update --packages curl # Selectively update specific package(s) sudo linux-updater release-upgrade -t 44 # Upgrade distribution release (Fedora/RHEL/Debian/Ubuntu) sudo linux-updater clean --all # Clean package cache and unused dependencies Subcommand Help: Run 'linux-updater --help' for options specific to that subcommand. Example: 'linux-updater release-upgrade --help' """, ) parser.add_argument( "-v", "--version", action="version", version=f"%(prog)s {__version__}", help="Show program's version number and exit.", ) subparsers = parser.add_subparsers(dest="command", help="Available subcommands") # Subcommand: update update_parser = subparsers.add_parser( "update", parents=[common], help="Inspect health, auto-remediate safe issues, and apply package updates.", formatter_class=argparse.RawDescriptionHelpFormatter, description="Inspect health, auto-remediate safe issues, and apply package updates.", epilog=""" Examples: sudo linux-updater update sudo linux-updater update -y sudo linux-updater update --dry-run sudo linux-updater update --packages nginx redis """, ) update_parser.add_argument( "--packages", nargs="+", metavar="PACKAGE", help="Selectively update only the specified package(s) instead of the entire system.", ) # Subcommand: check subparsers.add_parser( "check", parents=[common], help="Check system health and list available updates without making modifications.", formatter_class=argparse.RawDescriptionHelpFormatter, description="Check system health and list available updates without making modifications.", epilog=""" Examples: linux-updater check linux-updater check --json """, ) # Subcommand: release-upgrade release_parser = subparsers.add_parser( "release-upgrade", parents=[common], help="Perform a major distribution release upgrade with additional safety guardrails.", formatter_class=argparse.RawDescriptionHelpFormatter, description="Perform a major distribution release upgrade with safety checks (e.g. Fedora, Ubuntu, AlmaLinux/Rocky).", epilog=""" Target Release Specification: On Fedora and Red Hat-based systems, you must specify the target release version. Both '-t / --target-release' and '--releasever' are supported. Examples: sudo linux-updater release-upgrade -t 44 # Fedora: upgrade to version 44 sudo linux-updater release-upgrade --releasever 44 # Fedora: alias syntax sudo linux-updater release-upgrade -t 24.04 # Ubuntu/Debian: upgrade to 24.04 sudo linux-updater release-upgrade -t 9 # AlmaLinux / Rocky: upgrade to EL 9 sudo linux-updater release-upgrade -t 44 --dry-run # Simulate upgrade without applying """, ) release_parser.add_argument( "-t", "--target-release", "--releasever", dest="target_release", type=str, help="Specify target distribution version number/codename (e.g. 44 for Fedora, 24.04 for Ubuntu, 9 for AlmaLinux).", ) # Subcommand: clean clean_parser = subparsers.add_parser( "clean", parents=[common], help="Clean downloaded package cache and remove orphaned packages.", formatter_class=argparse.RawDescriptionHelpFormatter, description="Clean downloaded package cache and remove orphaned packages.", epilog=""" Examples: sudo linux-updater clean sudo linux-updater clean --all """, ) clean_parser.add_argument( "--all", action="store_true", help="Clean both package cache and autoremove unused dependencies.", ) # Subcommand: health subparsers.add_parser( "health", parents=[common], help="Run only the pre-flight health diagnostic checks.", formatter_class=argparse.RawDescriptionHelpFormatter, description="Run only the pre-flight health diagnostic checks and print a formatted report.", epilog=""" Examples: linux-updater health linux-updater health --json linux-updater health --no-remediation """, ) return parser def format_health_report(report) -> None: print("\nPre-flight Health Diagnostics:") print("-" * 65) for res in report.results: status_symbol = "[ PASS ]" if res.status.value == "PASS" else ( "[ WARN ]" if res.status.value == "WARN" else "[ FAIL ]" ) print(f"{status_symbol} {res.name:<22} {res.message}") print("-" * 65) status_text = "PASSED" if report.passed else "FAILED" print(f"Overall Pre-flight Status: {status_text}\n") def prompt_confirmation( prompt: str = "Do you want to proceed with updates? [Y/n]: ", default_yes: bool = True, ) -> bool: try: choice = input(prompt).strip().lower() if not choice: return default_yes return choice in ("y", "yes", "tak", "t") except (KeyboardInterrupt, EOFError): print("\nAborted.") return False def trigger_system_reboot( distro_id: str, is_release_upgrade: bool = False, runner: Optional[CommandRunner] = None, ) -> bool: import shutil if runner is None: runner = CommandRunner() cmd_candidates: List[List[str]] = [] if is_release_upgrade and distro_id.lower() == "fedora": cmd_candidates.append(["dnf5", "offline", "reboot"]) cmd_candidates.append(["dnf", "system-upgrade", "reboot"]) cmd_candidates.append(["systemctl", "reboot"]) cmd_candidates.append(["reboot"]) for cmd in cmd_candidates: exe = shutil.which(cmd[0]) or cmd[0] try: res = runner.run([exe] + cmd[1:]) if res.success: return True except Exception: continue return False def check_root_privileges() -> bool: if hasattr(os, "geteuid"): return os.geteuid() == 0 return True def main(argv: Optional[List[str]] = None) -> int: parser = create_parser() args = parser.parse_args(argv) if args.command is None: args.command = "update" non_interactive = getattr(args, "non_interactive", False) dry_run = getattr(args, "dry_run", False) no_remediation = getattr(args, "no_remediation", False) skip_preflight = getattr(args, "skip_preflight", False) json_output = getattr(args, "json", False) config_path = getattr(args, "config", "/etc/linux-updater.json") detector = DistroDetector() distro = detector.detect() if not json_output: print(f"Linux System Updater v{__version__}") print(f"Detected System: {distro.pretty_name} (Family: {distro.family.value})") if distro.family == DistroFamily.UNKNOWN: if not json_output: print(f"Error: Unsupported or unrecognized Linux distribution: {distro.distro_id}", file=sys.stderr) return 1 # Root privilege check for mutating operations mutating_commands = {"update", "release-upgrade", "clean"} if args.command in mutating_commands and not dry_run: if not check_root_privileges(): if json_output: print(json.dumps({ "success": False, "error": "permission_denied", "message": f"Root privileges (sudo) are required to execute '{args.command}'." }, indent=2)) else: print( f"Error: Root privileges (sudo) are required to execute '{args.command}'.\n" f"Please run with: sudo linux-updater {args.command}", file=sys.stderr, ) return 1 # Concurrency control: singleton instance lock instance_lock = InstanceLock() if not instance_lock.acquire(): holder_pid = instance_lock.get_holder_pid() holder_msg = f" (PID {holder_pid})" if holder_pid else "" if json_output: print(json.dumps({ "success": False, "error": "already_running", "message": f"Another instance of linux-updater is already running{holder_msg}." }, indent=2)) else: print( f"Error: Another instance of linux-updater is already running{holder_msg}. Aborting.", file=sys.stderr, ) return 1 try: return _run( args=args, distro=distro, non_interactive=non_interactive, dry_run=dry_run, no_remediation=no_remediation, skip_preflight=skip_preflight, json_output=json_output, config_path=config_path, ) finally: instance_lock.release() def _run( args: argparse.Namespace, distro, non_interactive: bool, dry_run: bool, no_remediation: bool, skip_preflight: bool, json_output: bool, config_path: str, ) -> int: if json_output: os.environ["LINUX_UPDATER_NO_STREAM"] = "1" config = UpdaterConfig.load(Path(config_path) if config_path else None) if non_interactive: config.non_interactive = True if no_remediation: config.auto_remediate = False if getattr(args, "auto_reboot", False): config.auto_reboot = True # Resolve log path according to standards (/var/log/linux-updater/) resolved_log: Optional[Path] = None if config.log_file: resolved_log = Path(config.log_file) elif config.log_dir: import datetime now_ts = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") log_dir = Path(config.log_dir) try: log_dir.mkdir(parents=True, exist_ok=True) resolved_log = log_dir / f"linux-updater-{now_ts}.log" # Maintain latest.log symlink atomically latest_symlink = log_dir / "latest.log" temp_symlink = log_dir / "latest.log.tmp" try: if temp_symlink.exists() or temp_symlink.is_symlink(): temp_symlink.unlink() os.symlink(resolved_log.name, str(temp_symlink)) os.replace(str(temp_symlink), str(latest_symlink)) except Exception: pass except Exception: resolved_log = None runner = CommandRunner(verbose=config.verbose, log_file=resolved_log) if resolved_log: runner._log(f"=== Linux System Updater v{__version__} started (Distro: {distro.pretty_name}, PID: {os.getpid()}) ===") manager = get_manager(distro.family, runner=runner, distro_info=distro) checker = HealthChecker(config=config, manager=manager) remediation = RemediationEngine(manager=manager) # 1. Health Command if args.command == "health": report = checker.run_all_checks() if json_output: print(json.dumps(report.to_dict(), indent=2)) else: format_health_report(report) return 0 if report.passed else 1 # 2. Clean Command if args.command == "clean": if not json_output: print("Cleaning package cache...") res_clean = manager.clean_cache() res_auto = None if getattr(args, "all", False): if not json_output: print("Removing unused dependencies...") res_auto = manager.autoremove() if json_output: print(json.dumps({ "clean_cache": res_clean.to_dict(), "autoremove": res_auto.to_dict() if res_auto else None, }, indent=2)) else: print("Clean operation completed successfully.") return 0 # 3. Pre-flight health checks (for update, check, release-upgrade) if not skip_preflight: report = checker.run_all_checks() if not report.passed: if config.auto_remediate: if not json_output: print("Pre-flight checks failed. Attempting automated safe remediation...") remediated_any = False for r in report.results: if r.status == CheckStatus.FAIL and remediation.can_remediate(r): if not json_output: print(f"-> Remediating: {r.name} ({r.remediation_id})...") if remediation.remediate(r): remediated_any = True if remediated_any: # Re-run checks report = checker.run_all_checks() if not report.passed: if json_output: print(json.dumps({"error": "preflight_failed", "report": report.to_dict()}, indent=2)) else: format_health_report(report) print("Error: Pre-flight checks failed and could not be remediated. Aborting updates.", file=sys.stderr) return 1 # 4. Check Command if args.command == "check": if not json_output: print("Checking for available package updates...") updates = manager.check_updates() if json_output: print(json.dumps({ "updates_count": len(updates), "updates": [{"package": u.package, "current_version": u.current_version, "new_version": u.new_version, "repo": u.repo} for u in updates] }, indent=2)) else: print(f"\nAvailable Updates ({len(updates)}):") print("-" * 65) for u in updates: print(f"• {u.package:<30} {u.current_version} -> {u.new_version}") print("-" * 65) return 0 # 5. Update Command if args.command == "update": packages = getattr(args, "packages", None) if not json_output: if packages: print(f"Preparing to update specific packages: {', '.join(packages)}") else: print("Checking available updates...") # If not selective, query updates for preview in interactive mode updates = [] if not packages and not config.non_interactive: updates = manager.check_updates() if not updates: if not json_output: print("System is already up to date. No updates needed.") return 0 if not json_output: print(f"\nAvailable Updates ({len(updates)}):") print("-" * 65) for u in updates[:20]: print(f"• {u.package:<30} {u.current_version} -> {u.new_version}") if len(updates) > 20: print(f"... and {len(updates) - 20} more packages.") print("-" * 65) # Interactive confirmation gate if not config.non_interactive and not dry_run: if not prompt_confirmation(): if not json_output: print("Operation cancelled by user.") return 3 if not json_output: print("\nApplying updates...") res = manager.apply_updates( packages=packages, dry_run=dry_run, non_interactive=config.non_interactive, ) if not res.success: if not json_output: print(f"\nUpdate failed with exit code {res.return_code}: {res.stderr}", file=sys.stderr) else: print(json.dumps({"success": False, "result": res.to_dict()}, indent=2)) return 1 if config.clean_after_update: if not json_output: print("Cleaning orphan packages...") manager.autoremove() reboot = manager.is_reboot_required() if json_output: triggered = False if config.auto_reboot and not dry_run: triggered = trigger_system_reboot(distro.distro_id, is_release_upgrade=False, runner=runner) print(json.dumps({ "success": True, "reboot_required": reboot.required, "reboot_reason": reboot.reason, "reboot_triggered": triggered, }, indent=2)) else: print("\nUpdates applied successfully!") if config.auto_reboot: if dry_run: print("[dry-run] Would execute: sudo systemctl reboot") return 0 reason_msg = f" ({reboot.reason})" if reboot.required else "" print(f"\nRebooting system automatically (--reboot enabled){reason_msg}...") ok = trigger_system_reboot(distro.distro_id, is_release_upgrade=False, runner=runner) if not ok: print("Error: Failed to initiate system reboot. Please reboot manually.", file=sys.stderr) return 1 return 0 elif reboot.required: print(f"\n[!] ATTENTION: A system reboot is required ({reboot.reason}).") if not config.non_interactive and not dry_run: prompt_msg = "A system reboot is required to apply changes. Reboot now? [y/N]: " if prompt_confirmation(prompt=prompt_msg, default_yes=False): print("Rebooting system...") ok = trigger_system_reboot(distro.distro_id, is_release_upgrade=False, runner=runner) if not ok: print("Error: Failed to initiate system reboot. Please reboot manually.", file=sys.stderr) return 1 return 0 else: print("Reboot cancelled. Please reboot your system manually at your earliest convenience.") return 2 else: print("Please reboot the system using: sudo systemctl reboot") return 2 return 0 # 6. Release-Upgrade Command if args.command == "release-upgrade": target = getattr(args, "target_release", None) if distro.distro_id.lower() == "fedora" and not target: current_ver = distro.version_id.strip() if distro.version_id else "" suggested = f"-t {int(current_ver) + 1}" if current_ver.isdigit() else "-t " if not json_output: print( f"\nError: Fedora major release upgrade requires specifying the target version.\n" f"Current system version: Fedora {distro.version_id or 'unknown'}\n\n" f"Usage:\n" f" sudo linux-updater release-upgrade -t \n" f" sudo linux-updater release-upgrade --releasever \n\n" f"Examples:\n" f" sudo linux-updater release-upgrade {suggested}\n" f" sudo linux-updater release-upgrade {suggested} --dry-run\n", file=sys.stderr, ) else: print(json.dumps({ "success": False, "error": "Target release version required for Fedora", "current_version": distro.version_id, }, indent=2)) return 1 if not json_output: print("\n" + "=" * 65) print(" WARNING: MAJOR DISTRIBUTION RELEASE UPGRADE") print("=" * 65) print(f"Target Release: {target if target else 'Latest available'}") print("This operation performs a major upgrade of core system components.") print("Ensure you have a recent system backup or snapshot before proceeding.") print("=" * 65 + "\n") if not config.non_interactive and not dry_run: prompt_msg = f"Are you absolutely sure you want to proceed with upgrade to {target or 'new release'}? [y/N]: " if not prompt_confirmation(prompt=prompt_msg, default_yes=False): if not json_output: print("Release upgrade cancelled by user.") return 3 if not json_output: print("\nStarting major release upgrade...") res = manager.release_upgrade( target_release=target, dry_run=dry_run, non_interactive=config.non_interactive, ) if not res.success: if not json_output: print(f"\nRelease upgrade failed: {res.stderr}", file=sys.stderr) else: print(json.dumps({"success": False, "result": res.to_dict()}, indent=2)) return 1 reboot = manager.is_reboot_required() is_fedora = distro.distro_id.lower() == "fedora" reboot_reason = ( "execute the offline upgrade transaction" if is_fedora else "boot into the new release" ) reboot_cmd = ( "sudo dnf system-upgrade reboot" if is_fedora else "sudo systemctl reboot" ) if json_output: triggered = False if config.auto_reboot and not dry_run: triggered = trigger_system_reboot(distro.distro_id, is_release_upgrade=True, runner=runner) print(json.dumps({ "success": True, "release_upgrade": True, "target_release": target, "reboot_required": True if not dry_run else reboot.required, "reboot_triggered": triggered, }, indent=2)) else: print("\nRelease upgrade preparation completed successfully!") if dry_run: if config.auto_reboot: print(f"[dry-run] Would execute: {reboot_cmd}") else: print(f"[dry-run] A system reboot would be required ({reboot_cmd}).") return 0 if config.auto_reboot: print(f"\nRebooting system automatically to {reboot_reason} (--reboot enabled)...") ok = trigger_system_reboot(distro.distro_id, is_release_upgrade=True, runner=runner) if not ok: print("Error: Failed to initiate system reboot. Please reboot manually.", file=sys.stderr) return 1 return 0 elif not config.non_interactive: prompt_msg = f"\nA system reboot is required to {reboot_reason}.\nReboot now? [y/N]: " if prompt_confirmation(prompt=prompt_msg, default_yes=False): print("Rebooting system...") ok = trigger_system_reboot(distro.distro_id, is_release_upgrade=True, runner=runner) if not ok: print("Error: Failed to initiate system reboot. Please reboot manually.", file=sys.stderr) return 1 return 0 else: print(f"\n[!] ATTENTION: A system reboot is required.") print(f" To complete the upgrade, run: {reboot_cmd}") return 2 else: print(f"\n[!] ATTENTION: A system reboot is required to {reboot_reason}.") print(f" To execute the upgrade, run: {reboot_cmd}") return 2 return 0 return 0 if __name__ == "__main__": sys.exit(main())