#!/bin/bash
# create dump for database and upload it to local mysql
# src=          server with source of db ( ip address or unix socket )
# dst=          server with destination of db  
# db=           db anme
# login=        login for connection
# password=     password
# Carefully! Ansible already provides values in quotes

#set -e

BY_TABLE=1      # if set to 1 it is create dump per table
                # Longer but more reliable for large databases
REPLACE=0       # relace destionation database or not

DEFAULT_CONF=/root/.my.cnf # can set login and password from file
DEFAULT_CONF_USAGE=0

LOGDIR=/opt/webdir/logs
[[ ! -d $LOGDIR ]] && mkdir -m 750 $LOGDIR

# test mandatory option and print error if not exists
test_variables() {
  for desc in "src=$src" "dst=$dst" "db=$db" "login=$login" "password=$password"; do
    var=$(echo $desc | cut -d'=' -f1)
    val=$(echo $desc | cut -d'=' -f2)

    if [[ -z "$val" ]]; then
      # test if login and password needed variables  
      if [[ ( "$var" == "login" ) || ( "$var" == "password" ) ]]; then
        if [[ ! -f "$DEFAULT_CONF" ]]; then
          echo "{\"changed\":false,\"failed\":true,\"msg\":\"option $var= is mandatory, you must define it or set in $DEFAULT_CONF file\"}"
          exit 1
        fi
        DEFAULT_CONF_USAGE=1  
      else
        echo "{\"changed\":false,\"failed\":true,\"msg\":\"option $var= is mandatory, you must define it\"}"
        exit 1
      fi
    fi
  done

  # replace existen DB
  REPLACE=0
  if [[ ( -n "$replace" ) && ( $(echo "$replace" | grep -wci 'yes') -gt 0 ) ]]; then
    REPLACE=1
  fi
  
  # dump database all at once or by table
  BY_TABLE=1
  if [[ ( -n "$by_table" ) && ( $(echo "$by_table" | grep -wci 'no') -gt 0 ) ]]; then
    BY_TABLE=0
  fi

  SITE_TYPE='link'    # if link - not dumped db, no dublicate 
  if [[ ( -n "$site_type" ) && ( $(echo "$site_type" | grep -wic 'kernel') -gt 0 ) ]]; then
    SITE_TYPE='kernel'
  fi
}

save_log(){
  message=$1
  log_file=$LOGDIR/create_dbs.log

  printf "%-15s: %s\n" "$(date +%Y/%m/%d:%H:%M:%S)" "$message" >> $log_file
}

# create dump db and upload it to dest
dump_db() {
  save_log "Start recreate DBs on slave server, REPLACE=$REPLACE BY_TABLE=$BY_TABLE"  
  
  if [[ "$SITE_TYPE" == "link" ]]; then
    save_log "SITE_TYPE=$SITE_TYPE dump only for kernels. nothing to do"
    echo "{\"changed\":false,\"msg\":\"SITE_TYPE=$SITE_TYPE dump only for kernels. nothing to do!\"}"
    exit 0
  fi

  # create command lines for mysqldump and mysql
  if [[ $DEFAULT_CONF_USAGE -eq 1 ]]; then
    src_mysqldump_cmd="mysqldump --opt --single-transaction --defaults-file=$DEFAULT_CONF"
    src_mysql_cmd="mysql --defaults-file=$DEFAULT_CONF"
    dst_mysql_cmd="mysql --defaults-file=$DEFAULT_CONF"
  else
    src_mysqldump_cmd="mysqldump --opt --single-transaction --user=$login --password=$password"
    src_mysql_cmd="mysql --user=$login --password=$password"
    dst_mysql_cmd="mysql --user=$login --password=$password"
  fi

  # src is host address or local socket?
  if [[ $(echo $src | grep -c '^/') -gt 0 ]]; then
    src_mysql_cmd=$src_mysql_cmd" --socket=$src"
    src_mysqldump_cmd=$src_mysqldump_cmd" --socket=$src"
  else
    src_mysql_cmd=$src_mysql_cmd" --host=$src"
    src_mysqldump_cmd=$src_mysqldump_cmd" --host=$src"
  fi

  # dst is host address or local socket
  if [[ $(echo $dst | grep -c '^/') -gt 0 ]]; then
    dst_mysql_cmd=$dst_mysql_cmd" --socket=$dst"
  else
    dst_mysql_cmd=$dst_mysql_cmd" --host=$src"
  fi

  # final touch
  src_mysql_cmd=$src_mysql_cmd" $db"
  src_mysqldump_cmd=$src_mysqldump_cmd" $db"

  # test if database exists on dst server, if exist => exit 
  if_db=$($dst_mysql_cmd \
   -e "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '$db'" 2>/dev/null)
  if [[ -n "$if_db" ]];then
    save_log "Found $db on server"
    if [[ $REPLACE -eq 0 ]]; then
      echo "{\"changed\":false,\"msg\":\"Database db=$db already exists. nothing to do!\"}"
      exit 0
    else
      save_log " REPLACE=$REPLACE and db will be replaced"
      $dst_mysql_cmd -e "drop database $db;"
      if [[ $? -gt 0 ]]; then
        save_log "  error occurred during drop db=$db"
        echo "{\"changed\":false,\"failed\":true,\"msg\":\"error occurred during creation db=$db\"}"
        exit 1
      else
        if_db=0
      fi
    fi
  fi

  # create database
  save_log "create $db"
  $dst_mysql_cmd -e "create database $db;"
  if [[ $? -gt 0 ]]; then
    save_log " error occurred during creation db=$db"
    echo "{\"changed\":false,\"failed\":true,\"msg\":\"error occurred during creation db=$db\"}"
    exit 1
  fi

  # recovery database by mysqldump of it tables: one by one
  save_log "start recovery data from $db; BY_TABLE=$BY_TABLE"
  if [[ $BY_TABLE -eq 1 ]]; then
    # get list of tables from master
    table_list=$($src_mysql_cmd  -N -e "show tables;" | awk '{print $1}')
    if [[ -z "$table_list" ]]; then
      save_log " cannot get list of tables from $db"
      echo "{\"changed\":false,\"msg\":\"there are no tables in database db=$db. nothing to do!\"}"
      exit 0
    fi

    # process table one by one, exit if error happened
    for table in $table_list; do
      save_log " $db - create table $table"
      $src_mysqldump_cmd $table | $dst_mysql_cmd $db >> $log_file 2>&1
      
      if [[ $? -gt 0 ]] ; then
        save_log "  $db - error while create $table"
        echo "{\"changed\":false,\"failed\":true,\"msg\":\"error occurred during recovery db=$db table=$table\"}"
        exit 1
      else
        save_log "  $db - create table $table complete"
      fi
    done
    err=0
  
  # recovery database by mysqldump of whole database
  else
     $src_mysqldump_cmd | $dst_mysql_cmd >> $log_file 2>&1
     err=$?
  fi

  if [[ $err -gt 0 ]]; then
    save_log "recovery $db complete"
    echo "{\"changed\":false,\"failed\":true,\"msg\":\"error occurred during database db=$db recovery\"}"
  else
    save_log "error while recovery $db"
    echo "{\"changed\":true,\"msg\":\"recovery database db=$db is complete\"}"
  fi

  exit $err

}

# get options from file
source ${1}

test_variables

dump_db
