BEGIN
DECLARE v_rdsrepl INT;
DECLARE v_mysql_version VARCHAR(20);
DECLARE v_called_by_user VARCHAR(50);
DECLARE v_sleep int;
DECLARE v_threads_running INT;
DECLARE sql_logging BOOLEAN;
select @@sql_log_bin into sql_logging;
Select count(1) into v_rdsrepl from mysql.rds_history where action = 'disable set master' and master_user = 'rdsrepladmin';
Select user() into v_called_by_user;
select version() into v_mysql_version;
SELECT COUNT(1) into v_threads_running FROM information_schema.processlist WHERE user = 'system user';
IF  v_rdsrepl > 0 and  v_called_by_user != 'rdsadmin@localhost'
THEN
 set @@sql_log_bin=off;
 Select 'Permission Denied: This instance is a RDS Read Replica.' as Message;
ELSEIF v_threads_running = 0
 THEN
     update mysql.rds_replication_status set called_by_user=v_called_by_user, action='reset slave', mysql_version=v_mysql_version, master_host=NULL, master_port=NULL where action is not null;
  commit;
  RESET SLAVE ALL;
  INSERT into mysql.rds_history(called_by_user, action, mysql_version) values (v_called_by_user,'reset slave', v_mysql_version);
  commit;
  Select 'Slave has been reset' as message;
 ELSE  
  call mysql.rds_stop_replication;
  select sleep(1) into v_sleep;
  update mysql.rds_replication_status set called_by_user=v_called_by_user, action='reset slave', mysql_version=v_mysql_version, master_host=NULL, master_port=NULL where action is not null;
  commit;
  select sleep(1) into v_sleep;
  RESET SLAVE ALL;
  INSERT into mysql.rds_history(called_by_user, action, mysql_version) values (v_called_by_user,'reset slave', v_mysql_version);
  commit;
  Select 'Slave has been reset' as message;
END IF;
set @@sql_log_bin=sql_logging;
END