#!/usr/bin/python

'''Like ksops, but in Python.

This is a drop-in replacement for ksops, but doesn't require you to 
compile anything or worry about version compatability between your
plugin and your kustomize binary.
'''

import argparse
import subprocess
import sys
import yaml


def parse_args():
    p = argparse.ArgumentParser()
    p.add_argument('--debug', action='store_true')
    p.add_argument('config')
    return p.parse_args()


def output_one_object(path, config):
    plaintext = subprocess.check_output(['sops', '-d', path])

    parsed = yaml.safe_load(plaintext)
    if 'behavior' in config:
        annotations = parsed.setdefault('metadata', {}).setdefault('annotations', {})
        annotations['kustomize.config.k8s.io/behavior'] = config['behavior']
    yield yaml.safe_dump(parsed)


def output_all_objects(configs):
    for config in configs:
        for path in config.get('files', []):
            yield from output_one_object(path, config)


def main():
    args = parse_args()
    with open(args.config) as fd:
        configs = yaml.safe_load_all(fd)

        try:
            print('---\n'.join(output_all_objects(configs)))
        except Exception as err:
            if args.debug:
                raise
            else:
                print('ERROR:', err, file=sys.stderr)
            
            return 1

        return 0


if __name__ == '__main__':
    sys.exit(main())
