#!/usr/local/easyops/python/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import ConfigParser

current_path = os.path.dirname(os.path.abspath(__file__))
PROJECT_PATH = os.path.dirname(current_path)
if PROJECT_PATH not in sys.path:
    sys.path.append(os.path.join(PROJECT_PATH, "scripts"))

import simplejson


def get_option_or_default(config_parser, host_id, section):
    if config_parser.get(host_id, section):
        return config_parser.get(host_id, section)
    if config_parser.has_section("ssh") and config_parser.get("ssh", section):
        return config_parser.get("ssh", section)
    return ""


def validate_host_config(host_config):
    if len(host_config["host_config_list"]) > 1:
        if not host_config["master"] or not host_config["slave"] or not host_config["arbiter"]:
            raise Exception("master or slave or arbiter not set")
    for conf in host_config["host_config_list"]:
        if not conf["ip"]:
            raise Exception("ip field not set")
        if not conf["port"]:
            raise Exception("port field not set")
        if not conf["auth"]:
            raise Exception("auth field not set")
        if not conf["username"]:
            raise Exception("username field not set")
        if conf["auth"] == "password" and not conf["password"]:
            raise Exception("auth is password but password field not set")
        if conf["auth"] == "keyfile" and not conf["key_file"]:
            raise Exception("auth is password but password field not set")


if __name__ == "__main__":
    if len(sys.argv) != 2:
        print "Usage: python ./cutover_hosts_ini.py path_to_hosts_ini"
        sys.exit(1)

    config_parser = ConfigParser.ConfigParser()
    with open(sys.argv[1]) as f:
        config_parser.readfp(f)

    host_config = {"host_config_list": [], "master": "", "slave": "", "arbiter": ""}
    for id in range(20):
        host_id = "host{0}".format(id+1)
        if not config_parser.has_section(host_id):
            break
        host = {
            "ip": config_parser.get(host_id, "ip"),
            "port": int(get_option_or_default(config_parser, host_id, "port")),
            "username": get_option_or_default(config_parser, host_id, "username"),
            "auth": get_option_or_default(config_parser, host_id, "auth"),
            "password": get_option_or_default(config_parser, host_id, "password"),
            "key_file": get_option_or_default(config_parser, host_id, "keyfile"),
        }
        if host["auth"] == "password":
            host["key_file"] = ""
        else:
            host["password"] = ""

        host_config["host_config_list"].append(host)
        if config_parser.get(host_id, "mysql_role") == "master":
            host_config["master"] = host["ip"]
        if config_parser.get(host_id, "mysql_role") == "slave":
            host_config["slave"] = host["ip"]
        if config_parser.get(host_id, "mongo_role") == "arbiter":
            host_config["arbiter"] = host["ip"]

    if len(host_config["host_config_list"]) == 1:
        host_config["master"] = host_config["host_config_list"][0]["ip"]

    validate_host_config(host_config)

    with open(os.path.join(PROJECT_PATH, "data", "hostConfig.json"), "w") as f:
        simplejson.dump(host_config, f)

    with open(os.path.join(PROJECT_PATH, "data", "installDone.json"), "w") as f:
        simplejson.dump({"install_done": True}, f)
