#!/usr/bin/python3

#* Source: http://packages.linuxmint.com/pool/main/u/ubuntu-system-adjustments/
import sys
import subprocess
import datetime

grub_title = "Utile OS"

# Log current datetime
now = str(datetime.datetime.now())
with open("/var/log/utile-grub-entry-adjust.log", "w") as log_file:
    log_file.write("%s\n" % now)

    # Adjust the grub title
    try:
        buffer = []
        existing_title = None
        needs_modification = False
        with open("/boot/grub/grub.cfg") as grub_file:
            in_10_linux_section = False
            for line in grub_file:
                if ("BEGIN /etc/grub.d/10_linux" in line):
                    in_10_linux_section = True
                elif ("END /etc/grub.d/10_linux" in line):
                    in_10_linux_section = False
                if (in_10_linux_section):
                    if ("menuentry" in line) or ("submenu" in line):
                        # Get the existing title from the 1st menuentry in the 10_linux section
                        if existing_title is None:
                            if "'" in line:
                                existing_title = line.split("'")[1]
                            elif '"' in line:
                                existing_title = line.split('"')[1]

                            existing_title = existing_title.split(",")[0]
                            log_file.write("Grub title found: %s\n" % existing_title)
                        if (existing_title != grub_title):
                            needs_modification = True
                            line = line.replace(existing_title, grub_title)
                        if "--class ubuntu" in line:
                            needs_modification = True
                            line = line.replace("class ubuntu", "class utile")
                    if ("$vt_handoff" in line):
                        needs_modification = True
                        """
						Is this necessary? Ubuntu doesn't even seem to be using vt_handoff anymore, even after applying all quilt patches.
                        After reviewing the grub2 source package's changelog, it seems that vt_handoff was dropped with grub2 2.14-2, right before Resolute was
                        released. Linux Mint's latest version is based on Noble, so this is unnecessary for Utile OS. We should maintain this code independently now.
                        """
                        line = line.replace("$vt_handoff", "")
                buffer.append(line)
        if (needs_modification):
            with open("/boot/grub/grub.cfg", "w") as grub_file:
                grub_file.writelines(buffer)
                log_file.write("Replaced title and/or vt_handoff in /boot/grub/grub.cfg\n")
    except Exception as e:
        # Best effort, whatever happens, don't fail the boot sequence
        log_file.write("Error when looking for grub title or replacing it: %s\n" % e)
