#!/bin/bash

set -e

run_mysql () {
  {{ mysql_bin }} --defaults-file="{{ mysql_conf }}" --protocol=socket "$@"
}

revoke_user () {
  DB=$1
  UNAME=$2
  if [ ! -z "$UNAME" ]; then
    echo "Revoking all grants for user '$USER'";
    run_mysql -Be "
    set sql_log_bin=0;
    REVOKE ALL PRIVILEGES, GRANT OPTION FROM '$UNAME';
    DROP USER IF EXISTS '$UNAME'@'%';
    DROP USER IF EXISTS '$UNAME'@'localhost';
    DROP USER IF EXISTS '$UNAME'@'::';
    FLUSH PRIVILEGES;
    "
  fi
}

# Disable SQL_LOG_BIN, repman_slave_definition database doesn't need to be replicated

cat << EOF > {{ tmp_dir }}/.script.sql
SET @@SESSION.SQL_LOG_BIN=0;
use repman_slave_definition;

CREATE TABLE IF NOT EXISTS \`slave\` (
  \`name\` varchar(80) NOT NULL,
  \`state\` tinyint(1) DEFAULT NULL,
  \`user\` varchar(80) NOT NULL,
  PRIMARY KEY (\`name\`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

UPDATE \`slave\` set \`state\`=false;
{% for name, user in database_name_list -%}
{%  if name -%}
REPLACE INTO \`slave\` VALUES ('{{ name }}', true, '{{ user }}');
{%  endif -%}
{% endfor -%}

EOF

# Update requested slaves database
OUTPUT="{{ tmp_dir }}/removed_db.txt"
run_mysql < {{ tmp_dir }}/.script.sql
rm -f {{ tmp_dir }}/.script.sql
run_mysql -NBe "set sql_log_bin=0;SELECT name, user FROM repman_slave_definition.slave WHERE state=false" > $OUTPUT

DBNAME=$(run_mysql --skip-column-names -Be "set sql_log_bin=0;SELECT name FROM repman_slave_definition.slave WHERE state=false");
RET=$?

if [ ! "$RET" = "0" ]; then
  echo "Mysql command failed: $DBNAME"
  exit $RET
fi

if [ -z "$DBNAME" ]; then
  echo "No database for slave to remove.";
fi

for NAME in $DBNAME; do
  if [ ! -z "$NAME" ]; then
    USER=$(grep -oP "$NAME\s*\K\w+" $OUTPUT);
    if [ ! -z "$USER" ]; then
      revoke_user $NAME $USER;
    fi
    echo "Deleting database $NAME..."
    run_mysql -e "set sql_log_bin=0;DROP DATABASE IF EXISTS $NAME";
    run_mysql -e "set sql_log_bin=0;DELETE FROM repman_slave_definition.slave WHERE name='$NAME'";
    echo "Done."
  fi
done
