import os
import shutil
import random
import platform
import subprocess
from glob import glob

from itest.utils import check_output


CWD = os.path.dirname(os.path.abspath(__file__))

# set osc certifications
OSC_CERT_DIR = os.path.expanduser('~/.config/osc/trusted-certs')
OSC_CERT_FROM = os.path.join(CWD, 'fixtures', 'conf_fixtures')
OSC_CERTS = [name.split('/')[-1] for name in glob(r'%s/*_[0-9]*.pem' % OSC_CERT_FROM)]

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

for osc_cert in OSC_CERTS:
    if not os.path.exists(os.path.join(OSC_CERT_DIR, osc_cert)):
        shutil.copy(os.path.join(OSC_CERT_FROM, osc_cert), OSC_CERT_DIR)

SUDO_PASSWD = os.environ.get('ITEST_SUDO_PASSWD', '123456')


def sample_files(path, k):
    files = [ os.path.join(path, name) for name in os.listdir(path) ]
    idx = random.sample(range(0, len(files)), min(k, len(files)))
    return [ files[i] for i in idx ]

def random_tests():
    path = os.path.join(CWD, 'cases')
    def squrash(a, b):
        a.extend(b)
        return a
    return reduce(squrash, [ sample_files(os.path.join(path, comp), 2)
        for comp in os.listdir(path) if os.path.isdir(os.path.join(path, comp))])

SUITES = {
    'fast': '!build&&!remotebuild',
    'daily': '!remotebuild',
    'pre-release': [
        'fast',
        os.path.join(CWD, 'cases', 'build', 'test_build_debug_ia32.case'),
        os.path.join(CWD, 'cases', 'build', 'test_build_incremental_arm.case'),
        os.path.join(CWD, 'cases', 'remotebuild', 'test_rb_-B_--status_and_--buildlog_function.case'),
        ],
    'random': random_tests(),
    'ref-updated': 'random',
    'patchset-created': 'random',
}

TZ = 'Asia/Shanghai'
