#!/usr/bin/env python3
# Script to run pkgcheck with a fake config used for more easily working
# with test data.

import os
import sys
import tempfile
import textwrap
from unittest.mock import patch

from pkgcore import const as pkgcore_const
from snakeoil.osutils import pjoin

# make sure to use git repo version of pkgcheck
main_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
src_dir = pjoin(main_dir, 'src')
sys.path.insert(0, src_dir)
from pkgcheck.scripts import run


with tempfile.TemporaryDirectory(prefix='pkgcheck-test-config-') as tempdir:
    stubrepo = pjoin(pkgcore_const.DATA_PATH, 'stubrepo')
    repo_dir = pjoin(main_dir, 'testdata', 'repos')
    with open(pjoin(tempdir, 'repos.conf'), 'w') as f:
        f.write(textwrap.dedent(f"""\
            [DEFAULT]
            main-repo = stubrepo
            [stubrepo]
            location = {stubrepo}
        """))
        for repo in os.listdir(repo_dir):
            f.write(f'[{repo}]\nlocation = {pjoin(repo_dir, repo)}\n')

    # create make.profile symlink
    profile_path = pjoin(stubrepo, 'profiles', 'default')
    os.symlink(profile_path, pjoin(tempdir, 'make.profile'))

    args = sys.argv[1:]
    try:
        if args[0] == 'scan':
            # ignore system/user config settings
            args = ['scan', '--config', 'no', '--cache-dir', tempdir] + args[1:]
    except IndexError:
        pass
    args = ['pkgcheck', '--config', tempdir] + args
    with patch('sys.argv', args):
        run('pkgcheck')
