Given the package destination directory, the spec file source and package
    sources, use mock to safely build the rpm defined in the spec file

    CLI Example:

    .. code-block:: bash

        salt '*' pkgbuild.build mock epel-7-x86_64 /var/www/html
                    https://raw.githubusercontent.com/saltstack/libnacl/master/pkg/rpm/python-libnacl.spec
                    https://pypi.python.org/packages/source/l/libnacl/libnacl-1.3.5.tar.gz

    This example command should build the libnacl package for rhel 7 using user
    mock and place it in /var/www/html/ on the minion

def build(runas,
          tgt,
          dest_dir,
          spec,
          sources,
          deps,
          env,
          template,
          saltenv='base',
          log_dir='/var/log/salt/pkgbuild'):
    '''
    Given the package destination directory, the spec file source and package
    sources, use mock to safely build the rpm defined in the spec file

    CLI Example:

    .. code-block:: bash

        salt '*' pkgbuild.build mock epel-7-x86_64 /var/www/html
                    https://raw.githubusercontent.com/saltstack/libnacl/master/pkg/rpm/python-libnacl.spec
                    https://pypi.python.org/packages/source/l/libnacl/libnacl-1.3.5.tar.gz

    This example command should build the libnacl package for rhel 7 using user
    mock and place it in /var/www/html/ on the minion
    '''
    ret = {}
    try:
        __salt__['file.chown'](path=dest_dir, user=runas, group='mock')
    except OSError as exc:
        if exc.errno != errno.EEXIST:
            raise
    srpm_dir = os.path.join(dest_dir, 'SRPMS')
    srpm_build_dir = tempfile.mkdtemp()
    try:
        srpms = make_src_pkg(srpm_build_dir, spec, sources,
                             env, template, saltenv, runas)
    except Exception as exc:
        shutil.rmtree(srpm_build_dir)
        log.error('Failed to make src package')
        return ret

    distset = _get_distset(tgt)

    noclean = ''
    deps_dir = tempfile.mkdtemp()
    deps_list = _get_deps(deps, deps_dir, saltenv)

    retrc = 0
    for srpm in srpms:
        dbase = os.path.dirname(srpm)
        results_dir = tempfile.mkdtemp()
        try:
            __salt__['file.chown'](path=dbase, user=runas, group='mock')
            __salt__['file.chown'](path=results_dir, user=runas, group='mock')
            cmd = 'mock --root={0} --resultdir={1} --init'.format(tgt, results_dir)
            retrc |= __salt__['cmd.retcode'](cmd, runas=runas)
            if deps_list and not deps_list.isspace():
                cmd = 'mock --root={0} --resultdir={1} --install {2} {3}'.format(tgt, results_dir, deps_list, noclean)
                retrc |= __salt__['cmd.retcode'](cmd, runas=runas)
                noclean += ' --no-clean'

            cmd = 'mock --root={0} --resultdir={1} {2} {3} {4}'.format(
                tgt,
                results_dir,
                distset,
                noclean,
                srpm)
            retrc |= __salt__['cmd.retcode'](cmd, runas=runas)
            cmdlist = [
                        'rpm',
                        '-qp',
                        '--queryformat',
                        '{0}/%{{name}}/%{{version}}-%{{release}}'.format(log_dir),
                        srpm]
            log_dest = __salt__['cmd.run_stdout'](cmdlist, python_shell=False)
            for filename in os.listdir(results_dir):
                full = os.path.join(results_dir, filename)
                if filename.endswith('src.rpm'):
                    sdest = os.path.join(srpm_dir, filename)
                    try:
                        __salt__['file.makedirs_perms'](name=srpm_dir, user=runas, group='mock')
                    except OSError as exc:
                        if exc.errno != errno.EEXIST:
                            raise
                    shutil.copy(full, sdest)
                    ret.setdefault('Source Packages', []).append(sdest)
                elif filename.endswith('.rpm'):
                    bdist = os.path.join(dest_dir, filename)
                    shutil.copy(full, bdist)
                    ret.setdefault('Packages', []).append(bdist)
                else:
                    log_file = os.path.join(log_dest, filename)
                    try:
                        __salt__['file.makedirs_perms'](name=log_dest, user=runas, group='mock')
                    except OSError as exc:
                        if exc.errno != errno.EEXIST:
                            raise
                    shutil.copy(full, log_file)
                    ret.setdefault('Log Files', []).append(log_file)
        except Exception as exc:
            log.error('Error building from %s: %s', srpm, exc)
        finally:
            shutil.rmtree(results_dir)
    if retrc != 0:
        raise SaltInvocationError(
             'Building packages for destination directory {0}, spec {1}, sources {2}, failed '
             'with return error {3}, check logs for further details'.format(
                dest_dir,
                spec,
                sources,
                retrc)
        )
    shutil.rmtree(deps_dir)
    shutil.rmtree(srpm_build_dir)
    return ret