diff --git a/main.py b/main.py index 7af56f4..010a953 100644 --- a/main.py +++ b/main.py @@ -10,6 +10,8 @@ import time import services.apt import services.mail +from socket import gethostname + from dotenv import load_dotenv from os import getenv from os.path import dirname, join @@ -20,29 +22,117 @@ import typer dotenv_path = join(dirname(__file__), ".env") load_dotenv(dotenv_path) -# TODO: Logging -# TODO: Email alerts + structure -# TODO: Use typer for CLI -# TODO: Fix readme and git.uthmn.com page for final release. -# TODO: Error handling all round +# FIXME: Error handling +# FIXME: Add json email list that if not added will use parameters +# FIXME: Handle no updates available app = typer.Typer() @app.command() -def main(): +def serve(): """ Checks for updates and emails hourly for security, daily for general as a daemon. """ - pass + @app.command() -def now(): +def now(receiver_email: str): """ Checks for apt upgrades and emails them then exits. """ - # TODO: Flag --now to run temporarily and just execute hourly tasks instantly then exit - pass + generate_email(receiver_email) + +def generate_email(receiver_email: str): + services.apt.require_root() + if not services.apt.detect_apt(): + print("Apt not found on this system.") + exit(1) + updates = services.apt.check_updates() + + # Get how many security updates are available + security_updates = 0 + for package in updates: + if package["security"]: + security_updates += 1 + + # Get how many total updates are available + total_updates = len(updates) + # Get how many general updates are available + general_updates = total_updates - security_updates + + # Get system hostname + hostname = gethostname() + + # Create email subject + subject = f"{hostname}> {security_updates} security updates, {general_updates} general updates available" + + # Iterate over each security package and create a list of updates in html + + security_chunks = "" + + for package in updates: + if not package["security"]: + continue + chunk = f''' + + {package} + {package["installed_version"]} + {package["latest_version"]} + {package["repo"]} + + ''' + + security_chunks += chunk + + security = f''' +

Security

+ + + + + + + + {security_chunks} +
PackageInstalledLatestRepository
+''' + # Iterate over each general package and create a list of updates in html + + general_chunks = "" + + for package in updates: + if package["security"]: + continue + chunk = f''' + + {package} + {package["installed_version"]} + {package["latest_version"]} + {package["repo"]} + + ''' + + general_chunks += chunk + + general = f''' +

General

+ + + + + + + + {general_chunks} +
PackageInstalledLatestRepository
+''' + + html += security + html += general + + services.mail.send_email(receiver_email, subject, html) + @app.callback() def callback(): """