#!/bin/env python
# -*- coding: utf-8 -*-

DOCUMENTATION = '''
---
module: upyun_marco
version_added: "beta"
short_description: get upyun facts
description:
    - get upyun related upyuns
options:
  filter:
    description:
      - match the variable name
    required: False
    default: all
    aliases: []
author: Min.Ai
'''

EXAMPLES = '''
get infomation of container named example

- hosts: upyun_host
  tasks:
  upyun_marco:
'''
 
import re
import os
import subprocess

class UpYunMarco:
    def __init__(self, module):
        self.module = module
        self.name = self.module.params.get('filter')

    def all_var(self):
        result = {}
        command = ['bash', '-c', 'set -a && source /etc/upyun.cfg && env']
        proc = subprocess.Popen(command, stdout = subprocess.PIPE)
        for line in proc.stdout:
            if '=' in line:
                (key, _, value) = line.partition("=")
                value = value.rstrip('\n')
                if key == "NGINX_UPSTREAM":
                   result[key] = [ i.split('#')[0] for i in value.split() ]
                elif key in ["REDIS_MARCO_PORT", "NGINX_LOG_DEV", "LVS_VIP_CTC", "LVS_VIP_CNC"]:
                   result[key] = value
                elif key == 'CDN_API_BOTH':
                   if value:
                       result[key] = value.split('#')[0].split('@')
                   else:
                       result[key] = []
        else:
            result['LVS_VIP_CTC'] = result.get('LVS_VIP_CTC','')
            result['LVS_VIP_CNC'] = result.get('LVS_VIP_CNC','')
            result['CDN_API_BOTH'] = result.get('CDN_API_BOTH',[])
            result['CONSISTENT_HASH'] = len(result['NGINX_UPSTREAM']) / 2

        proc.communicate()

#        get_ip_cmd = r"""/bin/awk -F= '/IPADDR/{if($2 %s "192.168.") printf("%%s ",$2)}' /etc/sysconfig/network-scripts/ifcfg-eth*"""
        get_ip_cmd = r"""ifconfig | sed -r -n 's@.*addr:(.*)Bcast:.*Mask:.*@\1@gp'|awk '{if($1 %s "192.168.") print $1}'"""
        result['PUBLIC_IP'] =  os.popen(get_ip_cmd % ("!~")).read().split()
        result['PRIVATE_IP'] = os.popen(get_ip_cmd % ("~")).read().split()

        result['MARCO_LISTEN_IP'] = result['PUBLIC_IP'][:]
        if result['CDN_API_BOTH']:
            for ip in result['CDN_API_BOTH']:
                if ip in result['MARCO_LISTEN_IP']:
                    result['MARCO_LISTEN_IP'].remove(ip)
#           result['MARCO_LISTEN_IP'] = list(set(result['MARCO_LISTEN_IP']) - set(result['CDN_API_BOTH']))

        if result['LVS_VIP_CNC']:
            result['MARCO_LISTEN_IP'].append(result['LVS_VIP_CNC'])
        if result['LVS_VIP_CTC']:
            result['MARCO_LISTEN_IP'].append(result['LVS_VIP_CTC'])
        return result

def main():
    module = AnsibleModule(
        argument_spec = dict(
            filter = dict(default=''), 
        )
    )

    try:
        facter = UpYunMarco(module)
        facts = facter.all_var()
        module.exit_json(changed=False, ansible_facts=facts)

    except Exception, e:
        module.fail_json(changed=False, msg=repr(e))

# import module snippets
from ansible.module_utils.basic import *
main()
