#!/usr/bin/python3
#
# Copyright (C) 2023 Red Hat, Inc.
#
# 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.

"""Lookup an entry for 2 keys in a yaml config file if not found it
returns the default value passed as the third argument. It looks for a
config.yaml in ~/.config/dci-pipeline/ and /etc/dci-pipeline.

For a yaml config file like this:

---
https://github.com/dci-labs/toto:
  github_token: titi
...

It can be called like that:

$ get-config-entry https://github.com/dci-labs/toto github_token "$DEFAULT_TOKEN"
titi

"""

import os
import sys

import yaml


def main(args):
    "Entry point"
    for config in (
        "/etc/dci-pipeline/config.yaml",
        os.path.expanduser("~/.config/dci-pipeline/config.yaml"),
    ):
        try:
            with open(config) as in_stream:
                data = yaml.load(in_stream, Loader=yaml.BaseLoader)
            print(data[args[0]][args[1]])
            return 0
        except (FileNotFoundError, KeyError):
            pass
    print(args[2])
    return 0


if __name__ == "__main__":
    if len(sys.argv) != 4:
        print(f"Usage: {sys.argv[0]} <key1> <key2> <default value>", file=sys.stderr)
        sys.exit(1)

    sys.exit(main(sys.argv[1:]))

# get-config-entry ends here
