#!/usr/bin/env python2
import shutil
import sys
import random
import argparse
import os
import subprocess

def read_file_as_str(file_path):
    if not os.path.isfile(file_path):
        raise TypeError(file_path + " does not exist")

    all_the_text = open(file_path).read()
    # print type(all_the_text)
    return all_the_text.strip()

def confirmStopSuccess(args):
    workpath = "{prefix}/{pt}/{prgname}".format(
        prefix=os.path.abspath(args.install_prefix), pt=str(args.protocol_port), prgname=str(args.prog_name)
    )
    pidfile = "{dt}/data/proxysql.pid".format(dt = workpath)
    proxysql_pid = ""
    try:
        proxysql_pid = read_file_as_str(pidfile)
    except TypeError as err:
        sys.stderr.write("read pid file error:{}".format(str(err)))
        exit(1);
    process_dir = os.path.join('/proc',str(proxysql_pid))
    return os.path.exists(process_dir)

def doKill(args):
    workpath = "{prefix}/{pt}/{prgname}".format(
        prefix=os.path.abspath(args.install_prefix), pt=str(args.protocol_port), prgname=str(args.prog_name)
    )
    pidfile = "{dt}/data/proxysql.pid".format(dt = workpath)
    proxysql_pid = ""
    try:
        proxysql_pid = read_file_as_str(pidfile)
    except TypeError as err:
        sys.stderr.write("read pid file error:{}".format(str(err)))
        return 

    # fetch mysqld_safe pid
    cmd0 = "ps -ef| grep {py_pid}| grep -v grep | grep proxysql ".format(py_pid = proxysql_pid)
    print cmd0
    try:
        output = subprocess.check_output(cmd0,shell=True)
        print output;
    except subprocess.CalledProcessError as e:
        return

    cmd = "ps -ef| grep {py_pid}| grep proxysql | grep -v grep| awk -F\" \" 'END {{printf $2 \" \" $3}}' | xargs kill -9".format(py_pid = proxysql_pid)
    print cmd
    os.system(cmd)



def rollback_installation(args):
    error_count = 0
    doKill(args)

    # 2. remove the related directory
    try:
        # 1.1 remove the MySQL binary residential directory
        runing_dir = os.path.abspath(args.install_prefix) + "/" + str(args.protocol_port)
        shutil.rmtree(runing_dir,ignore_errors=True)
    except OSError as err:
        sys.stderr.write("Remove the Instance data and log failed: {}".format(str(err)))
        error_count = error_count+1

    if error_count > 0:
      return False

    return True


if __name__ == "__main__":
    random.seed(str(sys.argv[1:]))
    parser = argparse.ArgumentParser(description="Uninstall the Proxysql Instance.")
    parser.add_argument("--protocol_port", type=int, help="Proxysql Instance Lisening port", required=True)
    parser.add_argument("--install_prefix", type=str,
        help="Proxysql installation directory prefix",
        required=True,
    )
    parser.add_argument("--prog_name", type=str,
        help="Proxysql package name",
        required=True,
    )
    args = parser.parse_args()

    ret = rollback_installation(args)

    if ret == False:
      exit(1)

    exit(0)
