#!/usr/bin/python3
# -*- coding: UTF-8 -*-
# © 2022, Multapplied Networks, Inc.

import json
import logging
import sys

from systemd.journal import JournalHandler as LogHandler

logger = logging.getLogger('bonding-authorized-keys')
if sys.stdout.isatty():
    logger.addHandler(logging.StreamHandler())
logger.addHandler(LogHandler())
logger.setLevel(logging.INFO)

NODE_CONFIG_FILE = "/var/lib/bonding/configuration.json"

class BondingConfigException(BaseException):
    pass

def read_node_configuration():
    """Parse any found node configuration as JSON and return it as a dictionary"""
    node_config = None
    try:
        with open(NODE_CONFIG_FILE) as conf:
            node_config = json.loads(conf.read())
    except OSError as e:
        raise BondingConfigException(f"Could not open bonding configuration file {NODE_CONFIG_FILE}: {e}")
    except ValueError as e:
        raise BondingConfigException(f"Could not parse bonding configuration file {NODE_CONFIG_FILE}: {e}")
    return node_config

def get_keys():
    config = read_node_configuration()
    if config:
        node_type = config['type']
        if "ssh_keys" in config[node_type]:
            key_string = ''
            for key in config[node_type]['ssh_keys']:
                key_string += str(key) + '\n'
            print(key_string)

if __name__ == "__main__":
    try:
        get_keys()
    except BondingConfigException as e:
        logger.error("Failed to read SSH keys from bonding configuration: %s" % e)
        sys.exit(1)
    except Exception:
        logger.exception("Unexpected error")
        sys.exit(1)