#!/usr/bin/python3
# coding: utf8
import os
import time

import gi

gi.require_version("Notify", "0.7")
from gi.repository import Notify
from gi.repository import GObject
from gi.repository import Gio, GLib

# file that signals a required reboot
REBOOT_FILE = "/var/run/reboot-required"
# in this period we will emit one gentle alert and wait
GRACE_PERIOD = 24 * 60 * 60
# after the grace period, we will emit an aggressive alert periodically
REMIND_INTERVAL = 60 * 60


def remaining_grace_time():
    return os.path.getctime(REBOOT_FILE) + GRACE_PERIOD - time.time()


def show_notification(notification):
    notification.close()
    if remaining_grace_time() <= 0:
        notification.set_timeout(Notify.EXPIRES_NEVER)
        notification.set_urgency(Notify.Urgency.CRITICAL)
        GLib.timeout_add(1000 * REMIND_INTERVAL, show_notification, notification)
    else:
        GLib.timeout_add(1000 * remaining_grace_time(), show_notification, notification)
    notification.show()
    return False


def reboot_notify(monitor, file, unknown, event):
    if event == Gio.FileMonitorEvent.ATTRIBUTE_CHANGED:
        n = Notify.Notification.new(
            "Reboot required",
            "The computer needs to be restarted to finish installing updates",
        )
        n.add_action(
            "reboot",
            "Reboot now",
            lambda _, __: os.system("gnome-session-quit --reboot"),
        )
        time.sleep(300)
        show_notification(n)


def main():
    Notify.init("Scibian")
    file = Gio.file_new_for_path(REBOOT_FILE)
    monitor = file.monitor_file(Gio.FileMonitorFlags.NONE, None)
    monitor.connect("changed", reboot_notify)
    GLib.MainLoop().run()


if __name__ == "__main__":
    main()
