#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# SPDX-FileCopyrightText: (c) 2023 SUSE LLC
#
# This file is part of obs-service-replace_using_package_version.
#
#   obs-service-replace_using_package_version 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.
#
#   obs-service-replace_using_package_version 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 obs-service-replace_using_package_version.  If not,
#   see <http://www.gnu.org/licenses/>.
#
"""
replace_with_build_flavor.py

Usage:
    replace_using_build_flavor.py -h
    replace_using_build_flavor.py --regex=REGEX --file=FILE --outdir=DIR
        [--file=FILE]
        [--parse-build-flavor=regex]

Options:
    -h,--help                      : show this help message
    --outdir=DIR                   : output directory
    --file=FILE                    : file to update
                                       The default build recipe file
                                       (e.g. Dockerfile) is used when this
                                       parameter is omitted.
    --regex=REGEX                  : regular expression for parsing file
    --parse-build-flavor=BFREGEX   : parse the build flavor using the regex and use the matching group
                                     as the string to replace the input file regex.
"""
from typing import Optional
import docopt
import re
import os
import subprocess
from rpm import labelCompare
from typing import List

version_regex = {
    'major': r'^(\d+)',
    'minor': r'^(\d+(\.\d+){0,1})',
    'patch': r'^(\d+(\.\d+){0,2})',
    'patch_update': r'^(\d+(\.\d+){0,3})',
    'offset': r'^(?:\d+(?:\.\d+){0,3})[+-.~](?:git|svn|cvs)(\d+)',
    'release': r'^(\d+(\.\d+){0,3}([+-.~](?:git|svn|cvs)([\d\w]+))?\-\d+(\.\d+){0,2})',  # noqa: E501
    'release_increment': r'^(\d+(\.\d+){0,3}([+-.~](?:git|svn|cvs)([\d\w]+))?\-\d+(\.\d+){0,3})',  # noqa: E501
}
allowed_version_regex = version_regex.keys()
obsinfo_regex = r'version: (.+)'

def main():
    """
    main-entry point for program, expects dict with arguments from docopt()
    """
    # TODO: probably there is a better way to set the repositories path
    command_args = docopt.docopt(__doc__)

    src_file = command_args['--file']

    if not os.path.isfile(src_file):
        raise RuntimeError('File {0} not found'.format(src_file))

    if not os.path.isdir(command_args['--outdir']):
        raise Exception(
            'Output directory {0} not found'.format(command_args['--outdir'])
        )

    filecopy = os.path.join(
        command_args['--outdir'], os.path.basename(src_file)
    )

    # Get BUILD_FLAVOR from env
    build_flavor = os.environ.get('BUILD_FLAVOR')
    if build_flavor is None:
        raise RuntimeError('No BUILD_FLAVOR env variable exists. Are we running a multibuild?')

    bf_regex_str = command_args['--parse-build-flavor']
    if bf_regex_str:
        bf_regex = r'{}'.format(bf_regex_str)
        m = re.search(bf_regex, build_flavor)
        if m is None:
            raise RuntimeError('BFREGEX "{}" does not match against BUILD_FLAVOR "{}"', bf_regex_str, build_flavor)
        if len(m.groups()) != 1:
            raise RuntimeError('More than a single match found: {}', m.groups())
        build_flavor = m.group(1)

    print("==== Replacing file '{}' regex='{}' with string '{}'", src_file, command_args['--regex'], build_flavor)

    apply_regex_to_file(
        src_file,
        filecopy,
        command_args['--regex'],
        build_flavor
    )


def apply_regex_to_file(input_file, output_file, regex, replacement):
    with open(input_file, 'r') as in_file:
        contents = in_file.read()

    with open(output_file, 'w') as out_file:
        out_file.write(re.sub(regex, replacement, contents))


def init(__name__):
    if __name__ == '__main__':
        main()


init(__name__)
