#!/usr/local/bin python3
import sys
import os
import pymysql
import configparser
import time

def connect_master(conf):
     try:
          conn = pymysql.connect(host='localhost',
                             user=conf.get('master','username'),
                             password=conf.get('master','password'),                             
                             db='mysql',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)
     except Exception as e:
        print(e)
        return False
     else:
        return conn
def connect_slave(conf):
     try:
          conn = pymysql.connect(host=conf.get('slave','host'),
                             user=conf.get('slave','username'),
                             password=conf.get('slave','password'),                           
                             db='mysql',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)
     except Exception:
        return False
     else:
        return conn
def check_slave(connection):
     status = -1
     try:
          cursor = connection.cursor(pymysql.cursors.DictCursor)
          cursor.execute("SHOW SLAVE STATUS")
          rows = cursor.fetchall()
          Slave_IO_Running = rows[0]['Slave_IO_Running']
          Slave_SQL_Running = rows[0]['Slave_SQL_Running']  
          if Slave_IO_Running != "Yes" or Slave_SQL_Running != "Yes":
               status = 0
          else:
               status = 1

     except Exception:
        return False
     else:
        return status
def get_pos_slave(connection,conf):
     text = ''
     try:
          cursor = connection.cursor(pymysql.cursors.DictCursor)
          cursor.execute("SHOW MASTER STATUS")
          rows = cursor.fetchall()
          File = rows[0]['File']
          Position = rows[0]['Position']
          text = "CHANGE MASTER TO MASTER_HOST='"+conf.get('master','host')+"', MASTER_USER='"+conf.get('replicator','username')+"', MASTER_PASSWORD='"+conf.get('replicator','password')+"', MASTER_LOG_FILE='"+File+"', MASTER_LOG_POS="+str(Position)
     except Exception:
        return False
     else:
        return text
def get_pos_master(connection,conf):
     text = ''
     try:
          cursor = connection.cursor(pymysql.cursors.DictCursor)
          cursor.execute("SHOW MASTER STATUS")
          rows = cursor.fetchall()
          File = rows[0]['File']
          Position = rows[0]['Position']
          text = "CHANGE MASTER TO MASTER_HOST='"+conf.get('slave','host')+"', MASTER_USER='"+conf.get('replicator','username')+"', MASTER_PASSWORD='"+conf.get('replicator','password')+"', MASTER_LOG_FILE='"+File+"', MASTER_LOG_POS="+str(Position)
     except Exception:
        return False
     else:
        return text
     
def set_slave(connection,conf):
     status = -1
     try:
          cursor = connection.cursor(pymysql.cursors.DictCursor)
          cursor.execute("SHOW MASTER STATUS")
          
     except Exception:
        return False
     else:
        return status
def print_green(text):
    print("\033[32m{}".format(text))
    print("\033[0m{}") 
def print_red(text):
    print("\033[31m{}".format(text))
    print("\033[0m{}") 
CONFIG_FILE = (os.path.join(os.path.dirname(__file__),'config.ini'))
conf = configparser.ConfigParser()
conf.read(CONFIG_FILE)
connection_master = connect_master(conf)
if connection_master:
     status = check_slave(connection_master)
     
     if status!=1:
          connection_slave = connect_slave(conf)
          if connection_slave:
               text = get_pos_master(connection_slave,conf)
               print(text)
               cursor = connection_master.cursor(pymysql.cursors.DictCursor)
               cursor.execute("STOP SLAVE")
               cursor.execute(text)
               cursor.execute("START SLAVE")
               connection_master.close()
               connection_slave.close()
               time.sleep(3)
               connection_master = connect_master(conf)
               if connection_master:
                    status = check_slave(connection_master)
                    if status==1:
                         conf.set('status','status','error')
                         
                         config.write(CONFIG_FILE)
                         print_green('REPLICATION SUCCESS')
                         connection_master.close()
                    else:
                         print_red('REPLICATION ERROR')
                         connection_master.close()
          else:
              print_red('Не удалось подключиться к базе данных SLAVE');           
     else:
          status = check_slave(connection_master)
          print_green('REPLICATION SUCCESS')
          connection_master.close()
     
else:     
     print_red('Не удалось подключиться к базе данных MASTER')
     
