#!/usr/libexec/platform-python
"""
    always:
        - unmount everything under /mnt/sysimage
        - unmount everything under /mnt/install

    image install:

        - populate a devicetree with only the image "disks"

    live install:

        - unmount everything under /media
        - populate a devicetree and tear down disk image stacks

"""
import os
import sys

live_install = "--liveinst" in sys.argv
image_install = False

# see if there are disk images to take down
sys_class_block = "/sys/class/block"
for dev in os.listdir(sys_class_block):
    if not dev.startswith("dm-"):
        continue

    uuid = open("%s/%s/dm/uuid" % (sys_class_block, dev)).read().strip()
    if uuid.startswith("ANACONDA-"):
        image_install = True
        break

import pyanaconda.anaconda_logging
pyanaconda.anaconda_logging.init(write_to_journal=False)

from blivet.devicetree import DeviceTree
from gi.repository import BlockDev as blockdev

disk_images = dict()

# find devices representing disk images
sys_class_block = "/sys/class/block"
for dev in os.listdir(sys_class_block):
    if not dev.startswith("dm-"):
        continue

    name = open("%s/%s/dm/name" % (sys_class_block, dev)).read().strip()
    uuid = open("%s/%s/dm/uuid" % (sys_class_block, dev)).read().strip()
    if not name or not uuid.startswith("ANACONDA-"):
        continue

    loop = os.listdir("%s/%s/slaves" % (sys_class_block, dev))[0].strip()
    disk_images[name] = blockdev.loop_get_backing_file(loop)

if not image_install:
    live_install = live_install or os.path.exists("/dev/live")

# unmount filesystems
for mounted in reversed(open("/proc/mounts").readlines()):
    (device, mountpoint, rest) = mounted.split(" ", 2)
    if mountpoint.startswith("/mnt/anactest") or mountpoint.startswith("/run/initramfs"):
        continue

    # Always clean up anaconda's mountpoints.
    if mountpoint.startswith("/mnt/sysimage") \
            or mountpoint.startswith("/mnt/install") \
            or mountpoint.startswith("/run/install"):
        os.system("umount %s" % mountpoint)

    # If this is for a live install, unmount any non-nodev filesystem that
    # isn't related to the live image.
    if ("/media" in mountpoint or device.startswith("/dev")) \
       and live_install and not "live" in device:
        os.system("umount %s" % mountpoint)

os.system("udevadm trigger --subsystem-match block")
os.system("udevadm settle")
devicetree = DeviceTree(disk_images=disk_images)
devicetree.populate(cleanup_only=True)
for name in devicetree.disk_images.keys():
    device = devicetree.get_device_by_name(name)
    for leaf in devicetree.leaves:
        if leaf.depends_on(device):
            leaf.teardown(recursive=True)
    device.deactivate(recursive=True)
