#!/usr/bin/python3
# This file is part of curtin. See LICENSE file for copyright and license info.

# This tool keeps a local copy of the maas images used by vmtests.
# It keeps only the latest copy of the available images.
import os
import random
import shutil
import subprocess
import sys
import time

# Fix path so we can import ImageStore class.
sys.path.insert(1, os.path.realpath(os.path.join(
                                    os.path.dirname(__file__), '..')))

from tests.vmtests import (
    IMAGE_DIR, IMAGE_SRC_URL, sync_images)
from tests.vmtests.image_sync import ITEM_NAME_FILTERS
from tests.vmtests.helpers import find_releases_by_distro
from curtin.util import get_platform_arch

DEFAULT_ARCH = get_platform_arch()


def _fmt_list_filter(filter_name, matches):
    return '~'.join((filter_name, '|'.join(matches)))

def _jenkins_runner_active():
    return subprocess.call(['pgrep', '-c', 'jenkins-runner'],
                           stdout=subprocess.PIPE)

if __name__ == '__main__':
    while _jenkins_runner_active() == 0:
        time_sleep = random.randint(5, 60)
        print("Not syncing while jenkins-runner is running. " +
               "Sleeping %s seconds." % time_sleep)
        time.sleep(time_sleep)

    if len(sys.argv) > 1 and sys.argv[1] == "--clean":
        print("cleaning image dir %s" % IMAGE_DIR)
        for subd in (".vmtest-data", "streams"):
            fp = os.path.join(IMAGE_DIR, subd)
            if os.path.exists(fp):
                print(" removing %s" % subd)
                shutil.rmtree(fp)
        if os.path.exists(IMAGE_DIR):
            for dirpath, dirnames, filenames in os.walk(IMAGE_DIR):
                for f in filenames:
                    if f.startswith("vmtest"):
                        fpath = os.path.join(dirpath, f)
                        print(" removing vmtest file %s" % fpath)
                        os.unlink(fpath)

    arg_releases = [r for r in sys.argv[1:] if r != "--clean"]
    arch_filters = ['arch={}'.format(DEFAULT_ARCH)]
    filter_sets = []
    if len(arg_releases):
        filter_sets.append([_fmt_list_filter('release', arg_releases),
                            _fmt_list_filter('krel', arg_releases)])
    else:
        for distname, distro in find_releases_by_distro().items():
            f = ['os={}'.format(distname),
                 _fmt_list_filter('release', distro.get('releases'))]
            # ensure we fetch release=x krel=x items
            krels = distro.get('krels')
            if krels:
                krels = set(krels).union(set(distro.get('releases')))
                f.append(_fmt_list_filter('krel', krels))
            filter_sets.extend([f])

    # Sync images.
    for filter_set in filter_sets:
        sync_images(IMAGE_SRC_URL, IMAGE_DIR, verbosity=2,
                    filters=filter_set + ITEM_NAME_FILTERS + arch_filters)

# vi: ts=4 expandtab syntax=python
