#!/bin/sh

. /usr/lib/lib-fliwi/ymc-common.sh


addToMySQL()
{
  if [ -n "$ymc_mysql_host" ]; then
    ymc_mysql_host_option="-h $ymc_mysql_host"
  else
    ymc_mysql_host_option=""
  fi

  if [ "$(echo $1 | grep -c 'TEST ACCESS QUIET')" -gt 0 ]; then
    echo "$1" | mysql -u $ymc_mysql_user $ymc_mysql_pw_option $ymc_mysql_host_option > /dev/null 2>&1
    return $?
  elif [ "$(echo $1 | grep -c 'TEST ACCESS VERBOSE')" -gt 0 ] || \
       [ "$(echo $1 | grep -c 'DROP ')" -gt 0 ]; then
    echo "$1" | mysql -u $ymc_mysql_user $ymc_mysql_pw_option $ymc_mysql_host_option > /dev/null
    return $?
  else
    echo "$1" | mysql -u $ymc_mysql_user $ymc_mysql_pw_option $ymc_mysql_host_option
    return $?
  fi
}

ymc_mysql_tools_get_credentials()
{
  ### Do some checks
  if [ "$(which fliwi-get-my-services)" = '' ]; then
    ymc_error_msg "Command 'fliwi-get-my-services' not found..."
    return 1
  fi

  ### Ask for the MySQL root password if needed
  addToMySQL "SELECT 'TEST ACCESS QUIET';"
  if [ $? -ne 0 ] && [ "$no_interaction" != 'yes' ]; then
    if [ "$(which dialog)" != '' ]; then
      ROOTPW=$(dialog --insecure --stdout --passwordbox "Enter MySQL ($ymc_mysql_user) PW:" 10 60)
    else
      read -rp "Enter MySQL ($ymc_mysql_user) PW: " ROOTPW
    fi
    echo ""
    ymc_mysql_pw_option=''
    if [ "$ROOTPW" != '' ]; then
      ymc_mysql_pw_option="--password="$ROOTPW
    fi
  fi

  addToMySQL "SELECT 'TEST ACCESS VERBOSE';"
  if [ $? -ne 0 ]; then
    ymc_error_msg "Communication with the mysql-server failed!"
    return 1
  fi

}

get_replication_information_dir()
{
  echo '/etc/fliwi/services/'$(get_own_db_service_prefix)'-mysql/ymc-mysql-config/replication-layout'
}


get_service_base_config_dir()
{
  echo '/etc/fliwi/services/'$(get_own_non_numbered_db_service)'/ymc-mysql-config/'$(get_own_db_service_numbered_type)
}


get_backup_base_dir()
{
  . $(get_replication_information_dir)'/simple.restore'
  if [ -n "$ymcMySqlBackupRootDir" ]; then
    if [ -d "$ymcMySqlBackupRootDir" ]; then
      final_dir=$ymcMySqlBackupRootDir'/'$(get_own_db_service_prefix)'-mysql-backup'
      if [ ! -d "$final_dir" ]; then
        mkdir -p $final_dir
        if [ $? -ne 0 ]; then
          ymc_error_msg "Failed to create dir '$final_dir'"
          return 1
        fi
      fi
      echo $final_dir
      return 0
    else
      ymc_error_msg "The MySQL backup-root dir '$ymcMySqlBackupRootDir' does not exists"
    fi
  else
    ymc_error_msg "Can not get the MySQL backup-root dir"
    return 1
  fi
}

get_maatkit_backup_dir()
{
  get_XYZ_backup_dir 'maatkit'
  return $?
}

get_structure_backup_dir()
{
  get_XYZ_backup_dir 'structure'
  return $?
}

get_automysql_backup_dir()
{
  get_XYZ_backup_dir 'automysqlbackup'
  return $?
}

get_XYZ_backup_dir()
{
  xyz="$1"
  backupBaseDir=$(get_backup_base_dir)
  if [ $? -ne 0 ]; then
    return 1
  fi

  ownDbService=$(get_own_db_service)
  if [ $? -ne 0 ]; then
    return 1
  fi

  echo $backupBaseDir/$xyz/$ownDbService
  return 0
}



############# ymc-mysql-setup-auto-import-mysql-backupdata //start

get_backup_source_hostname()
{
  is_ro_backup=$(fliwi-get-my-services | grep -c -E -e "^[a-z0-9-]+-mysql-bu")
  is_ro_slave=$(fliwi-get-my-services | grep -c -E -e "^[a-z0-9-]+-mysql-ro")
  is_rw_master=$(fliwi-get-my-services | grep -c -E -e "^[a-z0-9-]+-mysql-rw")
  is_ro_mirror=$(fliwi-get-my-services | grep -c -E -e "^[a-z0-9-]+-mysql-mi")
  if [ $is_rw_master -ne 0 ]; then
    ymc_info_msg "Got a master-host, trying to figure out the backup source..."
  elif [ $is_ro_mirror -ne 0 ]; then
    ymc_info_msg "Got a mirror-host, trying to figure out the backup source..."
  elif [ $is_ro_slave -ne 0 ]; then
    ymc_info_msg "Got a ro-slave-host, trying to figure out the backup source..."
  elif [ $is_ro_backup -ne 0 ]; then
    ymc_info_msg "Got a ro-backup-host, trying to figure out the backup source..."
  else
    ymc_error_msg "This host neither is a ro-slave nor a ro-backup nor a rw-master!"
    return 1
  fi

  my_own_db_service=$(get_own_db_service)
  if [ $? -ne 0 ]; then
    ymc_error_msg "Can not determine my own db-service while trying to figure out my backup-source"
    return 1
  fi
  tmp_backup_source=$(cat $(get_replication_information_dir)/simple.layout | grep -E -e '^[a-z0-9-]+-mysql-[a-z]{2}' | grep -v -E -e '^#' | grep -v -E -e '^[ ]*$' | grep -E -e '^[a-z0-9-]+-mysql-[a-z]{2}-[0-9]+ needsfrom [a-z0-9-]+-mysql-[a-z]{2}-[0-9]+$' | grep -E -e '^'$my_own_db_service | cut -d ' ' -f 3)
  if [ "$tmp_backup_source" != '' ] && \
     [ $(echo $tmp_backup_source | grep -c -E -e '^[a-z0-9-]+-mysql-bu-[0-9]+$') -eq 1 ]; then
    ymc_info_msg "Using '$tmp_backup_source' as source"
    echo $tmp_backup_source
    return 0
  else
    ymc_error_msg "The backup source '$tmp_backup_source' is invalid"
    return 1
  fi
}

find_sql_structure_file()
{
  use_backup_source_hostname="$1"
  file_name=$(echo $(ls $(get_backup_base_dir)/structure/$use_backup_source_hostname/* | grep "\.sql" | sort -r) | cut -d " " -f 1)
  echo $(find $(get_backup_base_dir)/structure/$use_backup_source_hostname/* | grep "$file_name" | sort) | cut -d " " -f 1
}

find_maatkit_import_dir()
{
  use_backup_source_hostname="$1"
  tmp_base_dir="$(get_backup_base_dir)/maatkit/$use_backup_source_hostname"
  if [ ! -d "$tmp_base_dir" ]; then
    ymc_error_msg "Base-Backup-Directory '$tmp_base_dir' does not exists"
    return 1
  fi
  dir_name=$(echo $(ls $tmp_base_dir | sort -r) | cut -d " " -f 1)

  tmp_final_dir="$(get_backup_base_dir)/maatkit/$use_backup_source_hostname/$dir_name/default"

  if [ ! -d "$tmp_final_dir" ] || \
     [ ! -f "$tmp_final_dir/00_master_data.sql" ]; then
    ymc_error_msg "Backup-Directory '$tmp_final_dir' does not exists"
    return 1
  fi
  echo $tmp_final_dir
  return 0
}




############# ymc-mysql-setup-auto-import-mysql-backupdata //end

get_own_db_service()
{
  my_own_db_service=$(fliwi-get-my-services | grep -E -e '^[a-z0-9-]+-mysql-[a-z]{2}-[0-9]+')
  if [ $? -ne 0 ] ||
     [ "$my_own_db_service" = "" ] ||
     [ $(echo $my_own_db_service | wc -w) -ne 1 ]; then
    return 1
  fi
  echo $my_own_db_service
  return 0
}

get_own_non_numbered_db_service()
{
  my_own_db_service=$(get_own_db_service)
  if [ $? -ne 0 ] ||
     [ "$my_own_db_service" = "" ] ||
     [ $(echo $my_own_db_service | wc -w) -ne 1 ]; then
    return 1
  fi
  echo $my_own_db_service | sed -r 's/-[0-9]+$//'
  return 0
}

get_own_db_service_numbered_type()
{
  my_own_db_service=$(get_own_db_service)
  if [ $? -ne 0 ] ||
     [ "$my_own_db_service" = "" ]; then
    return 1
  fi

  my_own_db_service_prefix=$(get_own_db_service_prefix)
  if [ $? -ne 0 ] ||
     [ "$my_own_db_service_prefix" = "" ]; then
    return 1
  fi

  echo $my_own_db_service | sed -r 's/^'$my_own_db_service_prefix'-mysql-//'
  return 0
}


get_own_db_service_prefix()
{
  my_own_db_service=$(get_own_db_service)
  if [ $? -ne 0 ] ||
     [ "$my_own_db_service" = "" ]; then
    return 1
  fi
  echo $my_own_db_service | sed -r 's/-mysql-[a-z]{2}-[0-9]+$//'
  return 0
}


############# ymc-mysql-setup-replication-from-freshly-installed-mysql-master //start

get_master_service_type()
{
  my_own_db_service=$(get_own_db_service)
    if [ $? -ne 0 ]; then
    ymc_error_msg "Can not determine my own db-service while trying to figure out the master to replicate from"
    return 1
  fi
  ymc_info_msg "Got a backup-host, using the local service '$my_own_db_service'"
  my_master_host=$(cat $(get_replication_information_dir)/simple.layout | grep -E -e '^[a-z0-9-]+-mysql-[a-z]{2}' | grep -v -E -e '^#' | grep -v -E -e '^[ ]*$' | grep -E -e '^[a-z0-9-]+-mysql-[a-z]{2}-[0-9]+ isslaveof [a-z0-9-]+-mysql-[a-z]{2}-[0-9]+$' | grep -E -e '^'$my_own_db_service | cut -d ' ' -f 3)
  if [ "$my_master_host" != '' ] && \
     [ $(echo $my_master_host | grep -c -E -e '^[a-z0-9-]+-mysql-(rw|mi)-[0-9]+') -eq 1 ]; then
    ymc_info_msg "Using '$my_master_host' as master-host..."
    echo $my_master_host
    return 0
  else
    ymc_error_msg "The master-host '$my_master_host' seems to be invalid !"
    return 1
  fi

  ymc_error_msg "This host not capable of doing replication with an other host!"
  return 1
}


############# ymc-mysql-setup-replication-from-freshly-installed-mysql-master //end




ymc_mysql_set_replication_auth()
{
  master_user=""
  master_password=""

  for user_raw_info in $(cat $(get_replication_information_dir)/simple.users | grep -v '^#' | grep -v -E -e '^[[:blank:]]*$' | sed -r 's/[ ]+/-,-,-,-/g')
  do
    user_info=$(echo $user_raw_info | sed -r 's/-,-,-,-/ /g')
    # USER PASSWORD DATABASE HOST Queries/h Updates/h Connect/h MaxConnect GRANT PERMISSIONS
    mysql_user=$(echo "$user_info" | cut -d ' ' -f 1)
    mysql_pass=$(echo "$user_info" | cut -d ' ' -f 2)
    mysql_database=$(echo "$user_info" | cut -d ' ' -f 3)
    mysql_host=$(echo "$user_info" | cut -d ' ' -f 4)
    mysql_max_queries_per_hour=$(echo "$user_info" | cut -d ' ' -f 5)
    mysql_max_updates_per_hour=$(echo "$user_info" | cut -d ' ' -f 6)
    mysql_max_connections_per_hour=$(echo "$user_info" | cut -d ' ' -f 7)
    mysql_max_parallel_connections=$(echo "$user_info" | cut -d ' ' -f 8)
    mysql_grant=$(echo "$user_info" | cut -d ' ' -f 9)
    mysql_permissions=$(echo "$user_info" | cut -d ' ' -f 10-)

    if [ "$mysql_user" = "replication" ] || \
       [ "$mysql_permissions" = "REPLICATION SLAVE" ]; then
      master_user=$mysql_user
      master_password=$mysql_pass
      break
    fi
  done

  if [ -z "$master_user" ] || \
     [ -z "$master_password" ]; then
    ymc_error_msg "Can not get master-auth-info. Please make sure you have either an user 'replication' or an user with an exclusive 'REPLICATION SLAVE'-permission!"
    return 1
  fi

  echo "ADDING REPLICATION AUTH (MASTER_USER + MASTER_PASSWORD)..."
  addToMySQL "CHANGE MASTER TO MASTER_USER='$master_user', MASTER_PASSWORD='$master_password';" || return 1
  return 0
}
