#!/bin/env python2
import argparse
import os
import sys
import getpass
import re
import time

localied_work_dir = ""
localied_conf_path = ""

def param_replace(string, rep_dict):
    pattern = re.compile("|".join([re.escape(k) for k in rep_dict.keys()]), re.M)
    return pattern.sub(lambda x: rep_dict[x.group(0)], string)

def prepare_directorys(args):
  global localied_conf_path
  global localied_work_dir
  localied_install_port_dir = "{ins_prefix}/{pt}".format(ins_prefix=args.install_prefix,pt=args.protocol_port)
  if os.path.exists(localied_install_port_dir):
    sys.stderr.write("{lipd} already exists".format(lipd=localied_install_port_dir))
    sys.exit(1)
  os.makedirs(localied_install_port_dir)
  
  # copy package to dest
  package_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  cmd = "cp -r {pkg} {lopr}".format(pkg= package_path,lopr=localied_install_port_dir)
  os.system(cmd)
  localied_work_dir = "{lopr}/{proxysql}".format(lopr=localied_install_port_dir,
                                    proxysql=args.prog_name)

def deal_conf(args):
  global localied_conf_path
  global localied_work_dir
  temp_conf_file = "{lwdr}/resource/proxysql.cnf.template".format(lwdr= localied_work_dir)
  
  localied_conf_path = "{lwdr}/etc/proxysql.conf".format(lwdr= localied_work_dir)
  config_template = open(temp_conf_file,'r').read()
  replace_items = {}
  replace_items['proxysql_data'] = localied_work_dir + '/data'
  replace_items['proxysql_log'] = localied_work_dir + '/data/proxysql.log'
  replace_items['proxy_admin'] = '0.0.0.0:'+str(args.admin_port)
  replace_items['proxy_interface'] = str(args.bind_address)+':'+str(args.protocol_port)

  conf_content = param_replace(config_template,replace_items)
  conf_file = open(localied_conf_path,'w')
  conf_file.write(conf_content)
  conf_file.close()

def boot_proxysql(args):
  global localied_conf_path
  global localied_work_dir

  cmd = "export LD_LIBRARY_PATH=\"{lwdr}/lib:$LD_LIBRARY_PATH\"; {lwdr}/bin/proxysql -c {cnffile} --idle-threads".format(
    lwdr= localied_work_dir, cnffile=localied_conf_path)

  ret = os.system(cmd)
  if ret != 0:
    sys.stderr.write("Start proxysql failed, please check the errorlog for more information")
    sys.exit(1)

if __name__ == "__main__":
  parser = argparse.ArgumentParser(description="Install proxysql node")
  parser.add_argument('--protocol_port',type=int,help="The port for connect proxysql",required=True)
  parser.add_argument('--admin_port',type=int,help="The port for admin proxysql",required=False)
  parser.add_argument('--install_prefix',type=str,help="Proxysql install prefix",required=True)
  parser.add_argument('--bind_address',type=str,help="The binding ip address of Proxysql",required=True)
  parser.add_argument("--prog_name", type=str,
        help="Proxysql package name",
        required=True,
    )
  args= parser.parse_args()

  # Prepare the related directorys
  prepare_directorys(args)

  # deal conf
  deal_conf(args)

  # boot proxysql
  boot_proxysql(args)
  sys.exit(0)
