#!/usr/bin/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 everything down

"""
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

# set the imageInstall flag so the logger won't log to the syslog
from pyanaconda.flags import flags
flags.imageInstall = True

import pyanaconda.anaconda_log
pyanaconda.anaconda_log.init()

from blivet import StorageDiscoveryConfig
from blivet.devicetree import DeviceTree
from blivet import devicelibs

storage_config = StorageDiscoveryConfig()

# 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()
    storage_config.diskImages[name] = devicelibs.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"):
        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 control --env=ANACONDA=1")
os.system("udevadm trigger --subsystem-match block")
os.system("udevadm settle")
devicetree = DeviceTree(conf=storage_config)
devicetree.populate(cleanupOnly=True)
devicetree.teardownAll()
for name in devicetree.diskImages.keys():
    device = devicetree.getDeviceByName(name)
    device.deactivate(recursive=True)
os.system("udevadm control --env=ANACONDA=0")

