"""
sbuild functions for for dmm.
"""

import os
import subprocess

def install(chroot, packages):
    """
    Install APT packages.

    chroot - specify chroot to do this in, False for host.
    """
    if chroot:
        result = os.system('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))
        return result
    else:
        result = os.system('LANG=C LANGUAGE=C LC_TYPE=C LC_MESSAGES=C '
                           'LC_ALL=C DEBIAN_FRONTEND=noninteractive '
                           'apt-get -y install %s' % (packages))
        return result


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

    chroot - specify chroot to do this in, False for host.
    """
    if chroot:
        os.system('chroot %s apt-get clean' % chroot)
    else:
        os.system('apt-get clean')


def update(chroot):
    """
    Update APT archives.
    """
    if chroot:
        os.system('chroot %s apt-get -q update' % (chroot))
    else:
        os.system('apt-get -q update')


def download_only(chroot, packages):
    """
    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:
            os.system('chroot %s apt-get -d -y --reinstall install %s'
                      % (chroot, package))
        else:
            os.system('apt-get -d -y --reinstall install %s' % (package))


def recipe_run(config, globalconf):
    """
    Perform actions for apt module
    """
    if config['action'] == 'install':
        if config['download_only']:
            # The use case for download only is mostly for cases like live
            # media preperation where we want to set up a package pool for
            # the media
            download_only(globalconf['chroot'], config['packages'])
        else:
            install(config['chroot'], config['packages'])

    elif config['update-sources']:
        update(globalconf['chroot'])

    if config['action'] == 'clean':
        clean(globalconf['chroot'])
    if config['clean_cache']:
        clean(globalconf['chroot'])

