#!/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 cache_packages, container_exists, create_podman_cmd, get_container_name, get_dirs, get_loader_container_name, get_name_from_container, install_packages_to_builder, mb_pull_loader_image
from hasherc.hshc_install_context import HshcInstallContext
from hasherc.utils import get_cache_dir, get_cfg
from hasherc_common.utils import print_error, run_cmd


if __name__ == '__main__':
    context = HshcInstallContext('0.4.0')

    try:
        context.name = get_name_from_container(context.root_package)
        get_container_name(context)
        get_loader_container_name(context)

        if not container_exists(context.container, context):
            print_error(f'Container {context.container} does not exist.')

        mb_pull_loader_image(context)

        cfg = get_cfg(context)
        get_cache_dir(cfg, context)

        get_dirs(context)

        files = cache_packages(context.req_packages, context)
        install_packages_to_builder(files, context)

    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')
