Create a platform specific source package from the given platform spec/control file and sources

    CLI Example:

    **Debian**

    .. code-block:: bash

        salt '*' pkgbuild.make_src_pkg /var/www/html/
                https://raw.githubusercontent.com/saltstack/libnacl/master/pkg/deb/python-libnacl.control.tar.xz
                https://pypi.python.org/packages/source/l/libnacl/libnacl-1.3.5.tar.gz

    This example command should build the libnacl SOURCE package and place it in
    /var/www/html/ on the minion

    dest_dir
        Absolute path for directory to write source package

    spec
        Absolute path to spec file or equivalent

    sources
        Absolute path to source files to build source package from

    env : None
        A list  or dictionary of environment variables to be set prior to execution.
        Example:

        .. code-block:: yaml

            - env:
                - DEB_BUILD_OPTIONS: 'nocheck'

        .. warning::

            The above illustrates a common PyYAML pitfall, that **yes**,
            **no**, **on**, **off**, **true**, and **false** are all loaded as
            boolean ``True`` and ``False`` values, and must be enclosed in
            quotes to be used as strings. More info on this (and other) PyYAML
            idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.

    saltenv: base

        Salt environment variables


    runas : root
        .. versionadded:: fluorine

        User to create the files and directories

        .. note::

            Ensure the user has correct permissions to any files and
            directories which are to be utilized.

def make_src_pkg(dest_dir, spec, sources, env=None, saltenv='base', runas='root'):
    '''
    Create a platform specific source package from the given platform spec/control file and sources

    CLI Example:

    **Debian**

    .. code-block:: bash

        salt '*' pkgbuild.make_src_pkg /var/www/html/
                https://raw.githubusercontent.com/saltstack/libnacl/master/pkg/deb/python-libnacl.control.tar.xz
                https://pypi.python.org/packages/source/l/libnacl/libnacl-1.3.5.tar.gz

    This example command should build the libnacl SOURCE package and place it in
    /var/www/html/ on the minion

    dest_dir
        Absolute path for directory to write source package

    spec
        Absolute path to spec file or equivalent

    sources
        Absolute path to source files to build source package from

    env : None
        A list  or dictionary of environment variables to be set prior to execution.
        Example:

        .. code-block:: yaml

            - env:
                - DEB_BUILD_OPTIONS: 'nocheck'

        .. warning::

            The above illustrates a common PyYAML pitfall, that **yes**,
            **no**, **on**, **off**, **true**, and **false** are all loaded as
            boolean ``True`` and ``False`` values, and must be enclosed in
            quotes to be used as strings. More info on this (and other) PyYAML
            idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.

    saltenv: base

        Salt environment variables


    runas : root
        .. versionadded:: fluorine

        User to create the files and directories

        .. note::

            Ensure the user has correct permissions to any files and
            directories which are to be utilized.
    '''
    _create_pbuilders(env, runas)
    tree_base = _mk_tree()
    ret = []
    if not os.path.isdir(dest_dir):
        os.makedirs(dest_dir)

    # ensure directories are writable
    root_user = 'root'
    retrc = 0
    cmd = "chown {0}:{0} {1}".format(runas, tree_base)
    retrc = __salt__['cmd.retcode'](cmd, runas='root')
    if retrc != 0:
        raise SaltInvocationError(
             "make_src_pkg ensuring tree_base \'{0}\' ownership failed with return error \'{1}\', "
             "check logs for further details".format(
                tree_base,
                retrc)
        )

    cmd = "chown {0}:{0} {1}".format(runas, dest_dir)
    retrc = __salt__['cmd.retcode'](cmd, runas=root_user)
    if retrc != 0:
        raise SaltInvocationError(
             "make_src_pkg ensuring dest_dir \'{0}\' ownership failed with return error \'{1}\', "
             "check logs for further details".format(
                dest_dir,
                retrc)
        )

    spec_pathfile = _get_spec(tree_base, spec, saltenv)

    # build salt equivalents from scratch
    if isinstance(sources, six.string_types):
        sources = sources.split(',')
    for src in sources:
        _get_src(tree_base, src, saltenv)

    # .dsc then assumes sources already build
    if spec_pathfile.endswith('.dsc'):
        for efile in os.listdir(tree_base):
            full = os.path.join(tree_base, efile)
            trgt = os.path.join(dest_dir, efile)
            shutil.copy(full, trgt)
            ret.append(trgt)

        return ret

    # obtain name of 'python setup.py sdist' generated tarball, extract the version
    # and manipulate the name for debian use (convert minix and add '+ds')
    salttarball = None
    for afile in os.listdir(tree_base):
        if afile.startswith('salt-') and afile.endswith('.tar.gz'):
            salttarball = afile
            break
    else:
        return ret

    frontname = salttarball.split('.tar.gz')
    salttar_name = frontname[0]
    k = salttar_name.rfind('-')
    debname = salttar_name[:k] + '_' + salttar_name[k+1:]
    debname += '+ds'
    debname_orig = debname + '.orig.tar.gz'
    abspath_debname = os.path.join(tree_base, debname)

    cmd = 'tar -xvzf {0}'.format(salttarball)
    retrc = __salt__['cmd.retcode'](cmd, cwd=tree_base, runas=root_user)
    cmd = 'mv {0} {1}'.format(salttar_name, debname)
    retrc |= __salt__['cmd.retcode'](cmd, cwd=tree_base, runas=root_user)
    cmd = 'tar -cvzf {0} {1}'.format(os.path.join(tree_base, debname_orig), debname)
    retrc |= __salt__['cmd.retcode'](cmd, cwd=tree_base, runas=root_user)
    cmd = 'rm -f {0}'.format(salttarball)
    retrc |= __salt__['cmd.retcode'](cmd, cwd=tree_base, runas=root_user, env=env)
    cmd = 'cp {0}  {1}'.format(spec_pathfile, abspath_debname)
    retrc |= __salt__['cmd.retcode'](cmd, cwd=abspath_debname, runas=root_user)
    cmd = 'tar -xvJf {0}'.format(spec_pathfile)
    retrc |= __salt__['cmd.retcode'](cmd, cwd=abspath_debname, runas=root_user, env=env)
    cmd = 'rm -f {0}'.format(os.path.basename(spec_pathfile))
    retrc |= __salt__['cmd.retcode'](cmd, cwd=abspath_debname, runas=root_user)
    cmd = 'debuild -S -uc -us -sa'
    retrc |= __salt__['cmd.retcode'](cmd, cwd=abspath_debname, runas=root_user, python_shell=True, env=env)
    cmd = 'rm -fR {0}'.format(abspath_debname)
    retrc |= __salt__['cmd.retcode'](cmd, runas=root_user)
    if retrc != 0:
        raise SaltInvocationError(
             'Make source package for destination directory {0}, spec {1}, sources {2}, failed '
             'with return error {3}, check logs for further details'.format(
                dest_dir,
                spec,
                sources,
                retrc)
        )

    for dfile in os.listdir(tree_base):
        if not dfile.endswith('.build'):
            full = os.path.join(tree_base, dfile)
            trgt = os.path.join(dest_dir, dfile)
            shutil.copy(full, trgt)
            ret.append(trgt)

    return ret