Skip to content

A hardened Linux desktop, rebuilt from scratch, with your Windows apps built in. Free and open source.

2.6 KB
Raw Blame
#!/usr/bin/python3 -I
"""The "Restore points" submenu of the start-up menu (Btrfs only).

Called by /etc/grub.d/15_wildos_recovery with the path of /boot as GRUB sees
it, the root filesystem's UUID and the kernel arguments. Each restore point
starts with its own kernel: the one still installed, or the copy kept in
/boot/wildos-restore when apt removed it. A point whose kernel is gone gets
no entry; going back from Settings or start-up recovery still works.
"""

import json
import os
import sys
import time

boot, uuid, args = sys.argv[1], sys.argv[2], sys.argv[3]
POINTS = "/boot/wildos-startup/points"


def for_manager(rows):
    """The same list for the start-up manager (wildos-startup), which runs
    before the disk holding the restore points is unlocked and starts a
    point by its entry here."""
    try:
        if rows:
            os.makedirs(os.path.dirname(POINTS), exist_ok=True)
            with open(POINTS + ".new", "w") as f:
                f.writelines(rows)
            os.replace(POINTS + ".new", POINTS)
        elif os.path.exists(POINTS):
            os.remove(POINTS)
    except OSError:
        pass


try:
    with open("/.snapshots/index.json") as f:
        index = json.load(f)
except (OSError, ValueError):
    for_manager([])
    sys.exit(0)


def kernel_for(point):
    for k in reversed(point.get("kernels") or []):
        for kern, init in (
            (f"/boot/vmlinuz-{k}", f"/boot/initrd.img-{k}"),
            (f"/boot/wildos-restore/{k}/vmlinuz-{k}", f"/boot/wildos-restore/{k}/initrd.img-{k}"),
        ):
            if os.path.exists(kern) and os.path.exists(init):
                return kern[len("/boot"):], init[len("/boot"):]
    return None


entries = []
for p in index.get("points", []):
    if p.get("kind") == "undo" and p.get("readonly_pending"):
        continue
    k = kernel_for(p)
    if k:
        entries.append((p, k))

if not entries:
    for_manager([])
    sys.exit(0)

rows = []
print("submenu 'Restore points' --class wildos-restore-points --unrestricted $menuentry_id_option 'wildos-restore-points' {")
for p, (kern, init) in entries:
    when = time.strftime("%-d %b %H:%M", time.localtime(p["time"]))
    title = f"{p['label']} ({when})".replace("'", "")
    rows.append(f"{p['id']}\t{title}\n")
    print(f"\tmenuentry '{title}' --class wildos-previous --unrestricted $menuentry_id_option 'wildos-point-{p['id']}' {{")
    print("\t\tload_video")
    print("\t\tinsmod gzio")
    print(f"\t\tlinux\t{boot}{kern} root=UUID={uuid} rootflags=subvol=@snapshots/{p['id']}/snapshot ro wildos.snapshot={p['id']} {args}")
    print(f"\t\tinitrd\t{boot}{init}")
    print("\t}")
print("}")
for_manager(rows)