#!/usr/bin/env python
# Copyright 2016 Atihita Inc.

import os
import shutil

from rpmUtils.miscutils import splitFilename


class Main(object):
    def __init__(self):
        pass

    def run(self):
        rpm_files = []

        for f in os.listdir('/var/lib/mock/amzn-latest-x86_64/result'):
            if f[-8:] == '.src.rpm':
                srpm_file = f
                continue

            if f[-4:] == '.rpm':
                rpm_files.append(f)
                continue

        print('SRPM: %s' % srpm_file)
        print('RPMs: %r' % rpm_files)

        (name, version, release, epoch, arch) = splitFilename(srpm_file)

        output_build_toppath = '/home/ll-user/mock-builder/build-artifacts/{name}/{version}/{release}'.format(
            name=name, version=version, release=release)

        if not os.path.exists(output_build_toppath):
            os.makedirs(output_build_toppath)

        srpm_pkg_path = '{toppath}/src'.format(toppath=output_build_toppath)
        if not os.path.exists(srpm_pkg_path):
            os.makedirs(srpm_pkg_path)
        shutil.copy(
            '/var/lib/mock/amzn-latest-x86_64/result/{srpm}'.format(
                srpm=srpm_file),
            srpm_pkg_path)

        for rpm in rpm_files:
            (n, v, r, e, a) = splitFilename(rpm)
            rpm_pkg_path = '{toppath}/{arch}'.format(
                toppath=output_build_toppath, arch=a)
            if not os.path.exists(rpm_pkg_path):
                os.makedirs(rpm_pkg_path)
            shutil.copy(
                '/var/lib/mock/amzn-latest-x86_64/result/{rpm}'.format(
                    rpm=rpm),
                rpm_pkg_path)


if __name__ == '__main__':
    main = Main()
    main.run()
