BEGIN
DECLARE v_rdsrepl INT;
DECLARE v_mysql_version VARCHAR(20);
DECLARE v_called_by_user VARCHAR(50);
DECLARE v_sleep 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;
IF v_rdsrepl > 0 and  v_called_by_user != 'rdsadmin@localhost'
THEN
set @@sql_log_bin=off;
Select 'RDS_SET_EXTERNAL_MASTER is disabled on this host.' as Message;
ELSE
SET @cmd = CONCAT('CHANGE MASTER TO ',
CONCAT_WS(', ',
CONCAT('MASTER_HOST = "', trim(both from host), '"'),
CONCAT('MASTER_PORT = ', port),
CONCAT('MASTER_USER = "', trim(both from user), '"'),
CONCAT('MASTER_PASSWORD = "', trim(both from passwd), '"'),
CONCAT('MASTER_LOG_FILE = "', trim(both from name), '"'),
CONCAT('MASTER_LOG_POS = ', pos),
CONCAT('MASTER_SSL = ', enable_ssl_encryption)));
PREPARE rds_set_master FROM @cmd;
update mysql.rds_replication_status set called_by_user=v_called_by_user, action='set master', mysql_version=v_mysql_version , master_host=trim(both from host), master_port=port where action is not null;
commit;
EXECUTE rds_set_master;
DEALLOCATE PREPARE rds_set_master;
INSERT into mysql.rds_history(called_by_user, action, mysql_version, master_host, master_port, master_user, master_log_file, master_log_pos, master_ssl)
values (v_called_by_user,'set master', v_mysql_version, trim(both from host), port, trim(both from user), trim(both from name), pos, enable_ssl_encryption);
commit;
 END IF;
set @@sql_log_bin=sql_logging;
END