"""
grub functions for for dmm.
"""

import os
from command_runner import command_runner

def grub_install(chroot, platform):
    """
    Install an appropriate grub version
    """
    ecode, result = command_runner("chroot %s apt-get -y -qq install grub-%s" % (chroot, platform))
    ecode, result = command_runner("chroot %s update-grub" % chroot)
    if platform == "efi":
        ecode, result = command_runner("chroot %s grub-install --force-extra-removable --target=x86_64-efi" % chroot)
    # hmm what happens if we have biosboot?
    return ecode, result


def recipe_run(config, globalconf):
    """
    Perform actions for grub module
    """
    if config['action'] == "mkrescue":
        return os.system('grub-mkrescue --modules="multiboot fat linux part_msdos minicmd ls iso9660" --output="%s" %s' % (config['isopath'], globalconf["live-media-path"]))
    if config['action'] == "create_legacy_boot_img":
        setup_grub_legacy_boot(globalconf["live-media-path"])


def setup_grub_legacy_boot(path):
    """
    Create PC BIOS (amd64/i386 legacy) bootable grub image.
    """
    # TODO: should probably happen inside the chroot?
    os.system('grub-mkstandalone --directory=/usr/lib/grub/i386-pc --format=i386-pc '
              '--themes="" --fonts="" --locales="" --modules="linux normal iso9660 '
              'biosdisk search png gfxmenu" --install-modules="linux normal iso9660 '
              'biosdisk memdisk search tar ls png gfxmenu" --output core.img')
    os.system('cat /usr/lib/grub/i386-pc/cdboot.img core.img > bios.img')


def depends():
    """
    Returns a list of dependencies for this module.
    Currently this is Debian packages.
    """
    return ({'xorriso': {"priority": "required", \
             "description": "command line ISO-9660 and Rock Ridge manipulation tool"},
             'mtools': {"priority": "required", \
             "description": "Tools for manipulating MSDOS files"}
           })

