#!/usr/bin/env python

import sys
import os

import yaml
import requests

CFG_PATH = '/etc/yeti/yeti-cli.yml'

def get_config(path):
    path = os.getenv('YETI_CMD_CFG_PATH', path)
    try:
        with open(path) as f:
            cfg = yaml.load(f)
    except IOError as e:
        print("Can't open config file {}, {}".format(path, e))
        sys.exit(1)
    except ScannerError as e:
        print("Can't parce config file {}, {}".format(path, e))
    return cfg


def main():
    cfg = get_config(CFG_PATH)
    u = cfg.get('authentificator_url')
    timeout = cfg.get('timeout')
    try:
        ans = requests.get(u, timeout=timeout)
        if int(requests.__version__.split('.')[0]) < 1:
            users = ans.json
        else:
            users = ans.json()
        for u in users:
            print 'environment="YETI_CMD_USER={0}" {1} {0}'.format(u['username'], u['ssh_key'])

    except BaseException as err:
        print "error: {}".format(err)
    except (requests.exceptions.ConnectionError, requests.exceptions.ReadTimeout) as err:
        print "error: {}".format(err)


if __name__ == '__main__':
    main()
