"""
apt functions for for dmm.
"""

from command_runner import command_runner


def install(packages="", chroot=None, **kwargs):
    """
    Install APT packages.

    chroot - specify chroot to do this in, False for host.
    """
    if chroot:
        ecode, result = command_runner('LANG=C LANGUAGE=C LC_TYPE=C '
                                       'LC_MESSAGES=C '
                                       'LC_ALL=C DEBIAN_FRONTEND=noninteractive '
                                       'chroot %s apt-get -y install %s'
                                       % (chroot,  packages), shell=True)
    else:
        ecode, result = command_runner('LANG=C LANGUAGE=C LC_TYPE=C '
                                       'LC_MESSAGES=C LC_ALL=C '
                                       'DEBIAN_FRONTEND=noninteractive '
                                       'apt-get -y install %s' %
                                       (packages), shell=True,
                                        live_output=True)
    return ecode, result


def clean(chroot=None):
    """
    Clean apt archives.

    chroot - specify chroot to do this in, False for host.
    """
    if chroot:
        ecode, result = command_runner('chroot %s apt-get clean' % chroot)
    else:
        ecode, result = command_runner('apt-get clean')
    return ecode, result


def update(chroot=None):
    """
    Update APT archives.
    """
    if chroot:
        ecode, result = command_runner('chroot %s apt-get -q update'
                                       % (chroot), shell=True,
                                          live_output=True)
    else:
        ecode, result = command_runner('apt-get -q update',
                                       shell=True, live_output=True)
    return ecode, result


def download_only(chroot=None, packages="", **kwargs):
    """
    Download packages for apt cache.
    For download-only, we do this one package at a time, since it's possible
    that some packages might conflict, and you might want to ship conflicting
    files on media.

    chroot - specify chroot to do this in, False for host.
    """
    for package in packages.split():
        if chroot:
            ecode, result = command_runner('chroot %s apt-get -d -y --reinstall install %s'
                      % (chroot, package))
        else:
            ecode, result = command_runner('apt-get -d -y --reinstall install %s' % (package))
    return ecode, result

