#!/usr/bin/env python3
'''
Copyright (C) 2025 Vladimir Vaskov <rirusha@altlinux.org>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see
<https://www.gnu.org/licenses/gpl-3.0-standalone.html>.

SPDX-License-Identifier: GPL-3.0-or-later
'''


import os

from hasherc.container_utils import build, cache_packages, container_exists, create_podman_cmd, gear_sources, get_build_requires, get_container_name, get_dirs, get_loader_container_name, get_package_info, init_rpm_cache, install_packages_to_builder, mb_pull_builder_image, mb_pull_loader_image, mb_pull_worker_image, run_builder
from hasherc.gear_hshc_context import GearHshcContext
from hasherc_common.utils import print_error, run_cmd

from hasherc.utils import get_cache_dir, get_cfg, get_env, get_packager, get_spec


if __name__ == '__main__':
    context = GearHshcContext('0.4.0')
    
    cur_con = None
    
    try:
        mb_pull_builder_image(context)
        mb_pull_loader_image(context)
        mb_pull_worker_image(context)

        # Init context
        cfg = get_cfg(context)
        _env = get_env(cfg, context)
        get_cache_dir(cfg, context)
        get_packager(cfg, context)
        get_spec(context)
        spec_name = os.path.basename(context.spec_path)
        get_package_info(context)
        get_container_name(context)
        get_loader_container_name(context)
        get_dirs(context)

        if context.rebuild:
            context.req_packages.append(context.name)
        if 'all' in context.req_packages:
            context.req_packages = os.listdir(context.cache_dir)
            for d in ['_cache', '_single']:
                if d in context.req_packages:
                    context.req_packages.remove(d)

        if context.rebuild and not container_exists(context.container, context):
            print_error(f'Container {context.container} does not exist.')
        
        if context.rebuild:
            pass
        else:
            init_rpm_cache(context)

        # Prepare gear SOURCES
        gear_src = gear_sources(context)
        print('Geared files:')
        print('\n'.join(gear_src))

        files_to_install = []

        build_reqs = get_build_requires(context)

        if build_reqs:
            if '/proc' in build_reqs:
                context.mountpoints.append('/proc')

            files_to_install = cache_packages(build_reqs, context)

            if context.verbose:
                print('\n'.join(files_to_install))

        if not context.rebuild:
            run_builder(_env, context)

        if files_to_install:
            install_packages_to_builder(files_to_install, context)

        build(context)

        print(f'Build of {context.name} {context.version}-{context.release} DONE.')
        print(f'Result located here: {context.pkg_out_dir}')
        print('\n'.join(map(lambda x: os.path.join(context.pkg_out_dir, x), os.listdir(context.pkg_out_dir))))
        print(f'Container {context.container} {'used' if context.rebuild else 'created'}.\n\nTo enter: \n\thshc-enter {context.name}\nTo remove: \n\thshc-stop {context.name}')

    except KeyboardInterrupt:
        print('')

        if container_exists(context.loader_container, context):
            run_cmd(
                create_podman_cmd(['stop', '-t', '0', context.loader_container], context),
                desc=None,
                silent=True,
                verbose=False,
                no_colors=context.no_colors
            )
            print_error(f'Loading stopped')
