"""
reprepro functions for for dmm.
"""

import os
import pathlib

def recipe_run(config, globalconf):
    """
    Perform actions for reprepro module
    """
    #TODO: break all these into smaller functions outside this one
    pkgpool_path = globalconf['workspace'] + "/pkgpool"
    path = pathlib.Path(globalconf['workspace'] + "/pkgpool/conf")
    path.mkdir(parents=True, exist_ok=True)

    package_path = config['prepend_path'] + "/" + config['package_path']
    version = globalconf['release']
    architectures = globalconf['architecture']
    components = config['components']
    description = globalconf['description']
    name = globalconf['name']

    reprepro_config = ("Origin: %s\nLabel: %s\nSuite: %s\nVersion: %s\nDescription: %s\n"
                       "Codename: %s\nComponents: %s\nArchitectures: %s\nUDebComponents: %s\n" %
                       (name, name, version, version, description, version, components, architectures, components))
    text_file = open(pkgpool_path + "/conf/distributions", "w")
    sources_write = text_file.write(reprepro_config)
    text_file.close()

    path = pathlib.Path(config['live-media-path'])
    path.mkdir(parents=True, exist_ok=True)

    # generate package pool
    # - usual debs:
    os.system('reprepro --ignore=extension -b %s includedeb %s %s' % (pkgpool_path, version, package_path + "/*.deb"))
    # - udebs, for installer:
    os.system('reprepro --ignore=extension -b %s includeudeb %s %s' % (pkgpool_path, version, package_path + "/*.udeb"))

    # Copy pkgpool to media
    os.system('cp -r %s %s %s' % (pkgpool_path + "/dists", pkgpool_path + "/pool", config['live-media-path'] + "/"))

    if config['clean_package_path']:
        os.system('rm %s/*.deb' % (config['prepend_path'] + config['package_path']))

