<gh_stars>0
#!/usr/bin/env python3
import os
import pathlib
import argparse
from jinja2 import Template

from common import load_flags, get_tasks, save_file, read_file


def build_if_not_exists(task_path):
    """Run make if there task binary don't exists in task_path"""
    if 'task' not in os.listdir(task_path):
        print(f'Building {task_path}...')
        os.system(f'cd {task_path} && make')


def copy_if_not_exists(task_folder, files):
    """Copy files into specified folder (overwrites if exists)"""
    for file in files:
        file_to_copy = pathlib.Path('./templates') / file
        print(f'Copying {file} to {task_folder}')
        os.system(f'cp {file_to_copy} {task_folder}')


def store_flag(task_folder, flag):
    print(f"Storing flag for {task_folder}")
    save_file(f'{task_folder}/flag.txt', f'{flag}\n')


def has_skip_file(task_folder, task_name, clean=False):
    """Check if there are .nobuild file in folder."""
    skipfile = task_folder / '.nobuild'
    if skipfile.exists():
        has_config = (task_folder / 'Dockerfile').exists() and (task_folder / 'nsjail.sh').exists()
        if not has_config and not clean:
            print(f'{task_name} requires manual configuration of Dockerfile and nsjail.sh')
        else:
            print(f'Skipping {task_name} due to .nobuild setting')

        return True

    return False


def build_docker_compose(tasks):
    print('Generating docker-compose.yml')

    def task_mapper(t):
        tname = t[0]
        return tname, 11300 + int(tname.split('-')[0])

    rendered = Template(read_file('./docker-compose.yml.jinja2')).render(
        tasks=list(map(task_mapper, tasks))
    )
    save_file(f'./docker-compose.yml', rendered)


def prepare_tasks(flags):
    tasks = get_tasks()
    for task_name, task_folder in tasks:
        print(task_name)
        flag = flags.get(task_name.split('-')[0])
        if not flag:
            raise SystemExit(f'{task_name} has not flag set - exiting')

        store_flag(task_folder, flag)

        if has_skip_file(task_folder, task_name):
            continue

        copy_if_not_exists(task_folder, ['Dockerfile', 'nsjail.sh'])
        build_if_not_exists(task_folder)

    build_docker_compose(tasks)
    print('Done!')


def cleanup_mode():
    def remove_file(file_path):
        if file_path.exists():
            print(f'Removing {file_path}')
            file_path.unlink()


    files_to_remove = ['Dockerfile', 'nsjail.sh']
    for task_name, task_folder in get_tasks():
        task_folder_path = pathlib.Path(task_folder)
        remove_file(task_folder_path / 'flag.txt')

        if has_skip_file(task_folder, task_name, True):
            continue

        for f in map(lambda x: task_folder_path / x, files_to_remove):
            remove_file(f)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Tasks builder')
    parser.add_argument('--clean', default=False, action='store_true',
                        help='clean up build files from every task folder')
    args = vars(parser.parse_args())

    if args.get('clean'):
        cleanup_mode()
    else:
        prepare_tasks(load_flags())

#!/usr/bin/env python3
import os
import pathlib
import argparse
from jinja2 import Template

from common import load_flags, get_tasks, save_file, read_file


def build_if_not_exists(task_path):
    """Run make if there task binary don't exists in task_path"""
    if 'task' not in os.listdir(task_path):
        print(f'Building {task_path}...')
        os.system(f'cd {task_path} && make')


def copy_if_not_exists(task_folder, files):
    """Copy files into specified folder (overwrites if exists)"""
    for file in files:
        file_to_copy = pathlib.Path('./templates') / file
        print(f'Copying {file} to {task_folder}')
        os.system(f'cp {file_to_copy} {task_folder}')


def store_flag(task_folder, flag):
    print(f"Storing flag for {task_folder}")
    save_file(f'{task_folder}/flag.txt', f'{flag}\n')


def has_skip_file(task_folder, task_name, clean=False):
    """Check if there are .nobuild file in folder."""
    skipfile = task_folder / '.nobuild'
    if skipfile.exists():
        has_config = (task_folder / 'Dockerfile').exists() and (task_folder / 'nsjail.sh').exists()
        if not has_config and not clean:
            print(f'{task_name} requires manual configuration of Dockerfile and nsjail.sh')
        else:
            print(f'Skipping {task_name} due to .nobuild setting')

        return True

    return False


def build_docker_compose(tasks):
    print('Generating docker-compose.yml')

    def task_mapper(t):
        tname = t[0]
        return tname, 11300 + int(tname.split('-')[0])

    rendered = Template(read_file('./docker-compose.yml.jinja2')).render(
        tasks=list(map(task_mapper, tasks))
    )
    save_file(f'./docker-compose.yml', rendered)


def prepare_tasks(flags):
    tasks = get_tasks()
    for task_name, task_folder in tasks:
        print(task_name)
        flag = flags.get(task_name.split('-')[0])
        if not flag:
            raise SystemExit(f'{task_name} has not flag set - exiting')

        store_flag(task_folder, flag)

        if has_skip_file(task_folder, task_name):
            continue

        copy_if_not_exists(task_folder, ['Dockerfile', 'nsjail.sh'])
        build_if_not_exists(task_folder)

    build_docker_compose(tasks)
    print('Done!')


def cleanup_mode():
    def remove_file(file_path):
        if file_path.exists():
            print(f'Removing {file_path}')
            file_path.unlink()


    files_to_remove = ['Dockerfile', 'nsjail.sh']
    for task_name, task_folder in get_tasks():
        task_folder_path = pathlib.Path(task_folder)
        remove_file(task_folder_path / 'flag.txt')

        if has_skip_file(task_folder, task_name, True):
            continue

        for f in map(lambda x: task_folder_path / x, files_to_remove):
            remove_file(f)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Tasks builder')
    parser.add_argument('--clean', default=False, action='store_true',
                        help='clean up build files from every task folder')
    args = vars(parser.parse_args())

    if args.get('clean'):
        cleanup_mode()
    else:
        prepare_tasks(load_flags())
#!/usr/bin/env python3 Run make if there task binary don't exists in task_path Copy files into specified folder (overwrites if exists) Check if there are .nobuild file in folder.