#!/usr/bin/env python3
#
# Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import pathlib
import yaml

import util
import product.model

dependency_type = util.check_env('DEPENDENCY_TYPE')
if not dependency_type == 'component':
    util.fail('don\'t know how to upgrade dependency type: ' + str(dependency_type))

component_reference = product.model.ComponentReference.create(
    name=util.check_env('DEPENDENCY_NAME'),
    version=util.check_env('DEPENDENCY_VERSION'),
)

images_file = pathlib.Path(
        util.check_env('REPO_DIR'),
        'charts',
        'images.yaml',
)

class ImagesParser(object):
    '''
    a naive YAML-parser crafted for the special case of processing
    gardener's images.yaml file; crafted that way to preserve comments/empty lines
    '''
    def __init__(
        self,
        images_file,
        names,
        target_version,
    ):
        self.images_file = images_file
        self.lines = images_file.read_text().split('\n')
        self.names = names
        self.target_version = target_version
        self._line_idx = 0

    def _line(self):
        return self.lines[self._line_idx]

    def _next_line(self):
        self._line_idx += 1
        return self._line()

    def _skip_to_next_entry(self, names):
        while not self._line().startswith('-'):
            self._next_line()
        name = self._line().strip().split(':')[-1].strip()

        if name not in names:
            self._next_line()
            return self._skip_to_next_entry(names)

        # found one of the entries:
        return name

    def _skip_to_next_tag(self):
        self._next_line()
        while not self._line().startswith('-'):
            if self._line().strip().startswith('tag:'):
                return
            self._next_line()
        raise RuntimeError('did not find tag attribute')

    def set_versions(self):
        while self.names:
            try:
                name = self._skip_to_next_entry(self.names)
            except IndexError:
                print(str(self.names))
                util.fail('don\'t know how to update ' + str(self.names))
            self.names.remove(name)
            self._skip_to_next_tag()
            tag_line = self._line()
            indent = len(tag_line) - len(tag_line.lstrip())
            patched_line = ' ' * indent + 'tag: "{version}"'.format(version=self.target_version)
            self.lines[self._line_idx] = patched_line

    def write_updated_file(self):
        self.images_file.write_text(
            '\n'.join(self.lines)
        )


# handle special cases
name = component_reference.github_repo()
if name == 'autoscaler':
    names = ['cluster-autoscaler']
elif name == 'vpn':
    names = ['vpn-seed', 'vpn-shoot']
elif name == 'external-dns-management':
    names = ['dns-controller-manager']
elif name == 'logging':
    names = ['fluent-bit-plugin-installer']
elif name == 'etcd-custom-image':
    names = ['etcd']
else:
    names = [name]


parser = ImagesParser(
    images_file=images_file,
    names=names,
    target_version=str(component_reference.version()),
)

parser.set_versions()
parser.write_updated_file()
