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

from mplatform.utils.db import dbbase
from mplatform.utils.net import network
from mplatform.config import SIGN_HOSTS_FILE,PRODUCT_SITE_CFG_PATH
import ethtool
import os
import commands
import socket
import re
import json
import shutil
import time

# 所有产品的站点信息
def allProductSites():
    if not os.path.exists(PRODUCT_SITE_CFG_PATH):
        return []
    product_sites = []
    try:
        p_site_cfgs = os.listdir(PRODUCT_SITE_CFG_PATH)
        
        for file in p_site_cfgs:
            site_id = file[:-4]
            cfg_dic = {}
            with open(PRODUCT_SITE_CFG_PATH + file,'r') as f:
                keys = ['name','logo','protocol','url','port']
                for line in f.readlines():
                    if line:
                        for key in keys:
                            if line.startswith(key+':'):
                                cfg_dic[key] = line[len(key) + 1:].replace('\n','').replace(' ','')
                                break
            # 没有url，直接忽略
            if not cfg_dic.get('url'):
                continue
            # 没有名称，设置默认名称
            if not cfg_dic.get('name'):
                cfg_dic['name'] = '未命名站点'
            # 判断url是否规范，开头需要'/'，不规范的补充
            if not cfg_dic['url'].startswith('/'):
                cfg_dic['url'] = '/' + cfg_dic['url']
                
            logo_dst = '/static/images/res/' + file
    
            # 拼接生成完整的url
            if not cfg_dic.get('protocol'):
                cfg_dic['protocol'] = 'http'
            site_url = '%s://<<<localip>>>:%s%s' % (cfg_dic['protocol'],cfg_dic['port'],cfg_dic['url'])
            site_dic = {'id':site_id,
                   'site_name':cfg_dic['name'],
                   'site_url':site_url,
                   'logo_path':logo_dst,
                   'logo_src':cfg_dic['logo']}
            product_sites.append(site_dic)
    except Exception as e:
        errorToLog('Error in allProductSites: %s' % str(e))
    return product_sites

def allProductBoot():
    return []
#     boot_cmds = []
#     try:
#         p_site_cfgs = os.listdir(PRODUCT_SITE_CFG_PATH)
#         
#         product_sites = []
#         key = 'boot:'
#         for file in p_site_cfgs:
#             site_id = file[:-4]
#             cfg_dic = {}
#             with open(PRODUCT_SITE_CFG_PATH + file,'r') as f:
#                 for line in f.readlines():
#                     if line and line.startswith(key):
#                         boot_cmds.append(line[len(key):].replace('\n',''))
#                         break
#     except Exception as e:
#         errorToLog('Error in allProductBoot: %s' % str(e))
#     return boot_cmds

# 将注册信息写入cache
def writeSignCache(sign_hosts):
    try:
        if not os.path.exists(SIGN_HOSTS_FILE):
            os.mknod(SIGN_HOSTS_FILE)
        with open(SIGN_HOSTS_FILE,'w') as f:
            f.truncate()
            f.write(json.dumps(sign_hosts))
    except Exception as e:
        errorToLog('Error in writeSignCache: %s' % str(e))

# 获取注册信息cache
def getSignCache():
    sign_hosts = {}
    try:
        if os.path.exists(SIGN_HOSTS_FILE):
            with open(SIGN_HOSTS_FILE,'r') as f:
                sign_hosts = json.loads(f.read())
    except Exception as e:
        errorToLog('Error in getSignCache: %s' % str(e))
    return sign_hosts

# 把管理中心的计算机名映射同步到运行端和客户端
def syncHostsConfig(target_ip = None):
    try:
        hosts = ''
        with open("/etc/hosts",'r') as f:
            for line in f.readlines():
                if line:
                    arr = line.split()
                    if len(arr) > 1 and re.match('^\d',arr[0]) and not arr[0].startswith('127.0.0.1'):
                        hosts += line
        msg = 'hosts_cfg %s' % hosts
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        if target_ip:
            s.sendto(msg, (target_ip, 20000))
        else:
            db = dbbase.database()
            hlist = db.select_fetchall("select ip from platdeploy_servicestatus union all select ip from platdeploy_terminalstatus")
            for h in hlist:
                s.sendto(msg, (h['ip'], 20000))
        s.close()
    except Exception as e:
        errorToLog('Error in syncHostsConfig: %s' % str(e))
"""
获取管理端、运行端、客户端的所有主机
"""
def get_all_hosts():
    hosts = []
    try:
        hosts = [get_local_ip()]
        sql = "select ip from platdeploy_servicestatus union  select ip from platdeploy_terminalstatus"
        db = dbbase.database()
        res = db.select_fetchall(sql)
        for h in res:
            hosts.append(h.get('ip'))
        hosts.sort()
    except Exception as e:
        errorToLog('Error in get_all_hosts: %s' % str(e))
    return hosts

def get_local_ip():
    try:
        ifnames = get_nics()
        for ifname in ifnames:
            config_file='/etc/sysconfig/network-scripts/ifcfg-%s' % ifname
            if os.path.exists(config_file):
                fp = open(config_file,'r')
                is_slave = False
                for line in fp.readlines():
                    if line[0] == '#':
                       continue
                    if 'SLAVE' in line and 'yes' in line:
                       is_slave = True
                       break
                    del line
                if not is_slave:
                    try:
                        ip = ethtool.get_ipaddr(ifname)
                        if ip:
                            return ip
                    except Exception as e:
                        errorToLog('Error in get_local_ip: %s' % str(e))
    except Exception as e:
        errorToLog('Error in get_local_ip: %s' % str(e))
    return ""

def get_nics():
    ifnames = []
    try:
        nic_list = network.all_ifaces()
        nics = [network.NIC(ifname) for ifname
                    in nic_list]
        bridges = [nic for nic in nics if nic.typ == "bridge"]
        vlans = [nic for nic in nics if nic.typ == "vlan"]
        nics = [nic for nic in nics if nic not in bridges + vlans]
        ifnames = [nic.ifname for nic in nics if nic.ifname <> 'lo']
    except Exception as e:
        errorToLog('Error in get_nics: %s' % str(e))
    return ifnames

def get_gateway():
    try:
        cmd = "route | grep default | awk '{print $2}'"
        (s,o) = commands.getstatusoutput(cmd)
        if s == 0 and o:
            return str(o)
    except Exception as e:
        errorToLog('Error in get_gateway: %s' % str(e))
    return ""

def errorToLog(errorMsg):
    errortime = time.strftime("%Y-%m-%d %H:%M:%S")
    errorinfo = '%s [ERROR] : %s' % (errortime,errorMsg)
    os.system('echo "%s" >> /var/log/mplatform/mplatform.log' % errorinfo)
