#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import os
import requests
import sys

BASE_DIR = os.path.dirname(os.path.realpath(__file__))


def get_init_info(clusterName, key, namespace='usa-init', appid='1', *args):
    cnf_url = 'http://uconf.service.ucloud.cn:8080/configfiles/json/'+appid+'/'+namespace+'/uops.' + clusterName
    hostname = 'uconf.service.ucloud.cn'
    ping_check = os.system("ping -c1 -w1 {0} &> /dev/null".format(hostname))
    all_info = {}
    if ping_check == 0:
        r = requests.get(cnf_url, timeout=5)
        if r.status_code == 200:
            all_info = r.json()
    if not all_info:
        offline_file = os.path.join(BASE_DIR, 'apollo/', clusterName + '.json')
        with open(offline_file) as f:
            all_info = json.load(f)
    # key = '.'.join(args[1:])
    if key == 'get_all_key_json':
        return json.load(all_info)
    if key == 'get_all_key_only':
        return '\n'.join([ v for k,v in all_info.items()])
    if key == 'get_all_key_value':
        return '\n'.join([ k+'='+v for k,v in all_info.items()])
    return all_info.get(key, '')


if __name__ == '__main__':
    if len(sys.argv) > 1:
        print(get_init_info(*sys.argv[1:]))

