#!/usr/bin/python
# Copyright (c) 2008 Alon Swartz <alon@turnkeylinux.org> - all rights reserved

import os
import debconf

from common import system

def deep_umount(target):
    paths = []
    for mount in file("/proc/mounts", 'r').readlines():
        path = mount.split()[1]
        if path.startswith(target):
            paths.append(path)

    paths.sort(reverse=True)
    for path in paths:
        try:
            system("umount -f %s" % path)
        except:
            pass

def reboot():
    template = 'di-live/reboot_now'

    debconf.runFrontEnd()
    db = debconf.Debconf()

    db.capb('backup')
    db.reset(template)
    db.input(debconf.HIGH, template)
    db.go()

    cmd = []
    fgvt = os.environ.get("FGVT")
    if fgvt:
        cmd.append("chvt %s" % fgvt)

    if db.getBoolean(template):
        cmd.append("systemctl reboot")

    if cmd:
        system("; ".join(cmd))

def main():
    deep_umount('/target')
    file('/tmp/.di-live-finalize', 'w').write('')
    reboot()


if __name__ == "__main__":
    main()

