# -*- coding: utf-8 -*-
#
!/usr/bin/env python
#
##################################################
#
Teach wisedom to my machine,please call me Croco#
#
 定时更改/etc/hosts 实现不修改程序的情况下,使得程序
#
 curl url 自动解析到内网IP
#
#################################################
from DebugLogger import  *
Logger.init("updatehost")
import os
import sys
import time
import json
import random

special_host = "chelun.eclicks.cn"
last_data = ""
last_line=""


def selectAnotherIp(iplist,last_ip):
    if last_ip in iplist:
        iplist.remove(last_ip)
    if len(iplist) == 0:
        return ""
    return random.choice(iplist)



def readWebConfAndGetNewIp(last_ip):
    file_name = "web.conf"
    if not os.path.exists(file_name):
        log("not exits such file:{0}".format(file_name))
        sys.exit(0)
        return  ""
    old_data = ""
    with open(file_name, "r") as f:
        old_data = f.read()
    if not old_data:
        log("get empty file:{0}".format(file_name))
        return ""
    iplist = []
    try:
        js_obj = json.loads(old_data)
        for item in js_obj["servers"]:
            if item["status"] == "online":
                iplist.append(item["host"])
    except:
        log("read failed from webserver_conf:" + file_name + "data:" + old_data)
        return ""
    return selectAnotherIp(iplist,last_ip)




def task():
    global last_data
    global special_host
    file_name = "hosts.conf"
    file_bak_name ="hosts2.conf"
    if not os.path.exists(file_name):
        log("not exits such file:{0}".format(file_name))
        sys.exit(0)
        return
    old_data = ""
    with open(file_name,"r") as f:
        old_data = f.readlines()
    if not old_data:
        log("get empty file:{0}".format(file_name))
        return
    if last_data == old_data:
        return
    line_list1=[]
    line_list2 = []
    for line in old_data:
        line = line.strip()
        if not line:
            continue
        if "#" in line:
            line_list1.append(line)
            line_list2.append(line)
            continue
        if special_host  not in line:
            line_list1.append(line)
            line_list2.append(line)
            continue
        line_list1.append(line)
        arr= line.split(" ")
        if len(arr) != 2:
            log("error line:{0}".format(line))
            sys.exit(1)
            return
        ipaddr = arr[0]
        newipaddr = readWebConfAndGetNewIp(ipaddr)
        if not newipaddr:
            log("not need to change")
            return
        line = newipaddr+" "+special_host
        line_list2.append(line)
        log("change ipaddr:{0} -> newipaddr:{1}".format(ipaddr,newipaddr))


    if os.path.exists(file_bak_name):
        os.remove(file_bak_name)
    with open(file_bak_name,"w") as f:
        for line in line_list1:
            f.write(line)
            f.write("\n")
    os.remove(file_name)
    with open(file_name,"w") as f:
        for line in line_list2:
            f.write(line)
            f.write("\n")
    if not os.path.exists(file_name):
        log("update failed,file:{0}".format(file_name),2)
        return
    log("update succ,file:{0}".format(file_name))
    with open(file_name,"r") as f:
        last_data = f.readlines()

    pass


def main():
    uid = os.getuid()
    if uid != 0:
        log("os.getuid() != 0,current uid:{0}".format(uid))
        return
    while True:
        task()
        time.sleep(60)

    pass

if __name__ == '__main__':
    task()
    #main()