#!/bin/bash

PATH=/usr/local/bin:/usr/local/sbin:/opt/local/bin:/usr/bin:/usr/sbin:/bin:/sbin

sqlmagic_fix() {
  if [ -f "$source" ] ; then
    cat $source | sed 's|/\\*!50001 CREATE ALGORITHM=UNDEFINED \\*/|/\\*!50001 CREATE \\*/|g; s|/\\*!50017 DEFINER=`[^`]*`@`[^`]*`\s*\\*/||g' | sed '/\\*!50013 DEFINER=.*/ d' > $target
    sed -i "s/^INSERT INTO/INSERT IGNORE INTO/g" $target
    echo "Fixed database dump stored as $target"
    exit 0
  else
    echo "ERROR: specified file $source does not exist"
    exit 1
  fi
}

sqlmagic_convert() {
  if [ ! -L "$HOME/static" ] ; then
    echo "ERROR: you must be logged in as a limited shell main user, typically o1.ftp"
    exit 1
  fi
  if drush status | grep "Successful" > /dev/null && [ -e "$HOME/static" ] ; then
    echo "It may take a long time, please wait..."
    if [ "$kind" = "to-myisam" ] ; then
      _THIS_DB=`drush status | grep "Database name" | cut -d: -f2 | awk '{ print $1}'`
      _THIS_SHOW="select TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = '$_THIS_DB' and TABLE_TYPE = 'BASE TABLE'"
      drush sql-query "$_THIS_SHOW" | tail -n +2 | xargs -I '{}' echo "ALTER TABLE {} ENGINE=MYISAM;" > $HOME/static/to_myisam_alter_table.sql
      sed -i "s/.*TABLE_NAME.*//g; s/ *$//g; /^$/d" $HOME/static/to_myisam_alter_table.sql &> /dev/null
      perl -p -i -e 's/(ALTER TABLE (cache_[a-z_]+|cache|sessions|users|watchdog|accesslog) ENGINE=)MYISAM/\1INNODB/g' $HOME/static/to_myisam_alter_table.sql
      drush sqlc < $HOME/static/to_myisam_alter_table.sql
      echo "This site database has been converted to MyISAM"
      rm -f $HOME/static/to_myisam_alter_table.sql
      exit 0
    elif [ "$kind" = "to-innodb" ] ; then
      _THIS_DB=`drush status | grep "Database name" | cut -d: -f2 | awk '{ print $1}'`
      _THIS_SHOW="select TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = '$_THIS_DB' and TABLE_TYPE = 'BASE TABLE'"
      drush sql-query "$_THIS_SHOW" | tail -n +2 | xargs -I '{}' echo "ALTER TABLE {} ENGINE=INNODB;" > $HOME/static/to_innodb_alter_table.sql
      sed -i "s/.*TABLE_NAME.*//g; s/ *$//g; /^$/d" $HOME/static/to_innodb_alter_table.sql &> /dev/null
      perl -p -i -e 's/(search_[a-z_]+ ENGINE=)INNODB/\1MYISAM/g' $HOME/static/to_innodb_alter_table.sql
      drush sqlc < $HOME/static/to_innodb_alter_table.sql
      echo "This site database has been converted to InnoDB"
      rm -f $HOME/static/to_innodb_alter_table.sql
      exit 0
    else
      echo "Invalid target format - use either to-myisam or to-innodb"
      exit 1
    fi
  else
    echo "ERROR: you must run this command from the site directory"
    echo "ERROR: cd /path/to/platform/sites/domain first"
    exit 1
  fi
}

case "$1" in
  fix) source="./$2"
       target="./fixed-$2"
       sqlmagic_fix
  ;;
  convert) kind="$2"
       sqlmagic_convert
  ;;
  *)   echo "Usage: sqlmagic {fix file.sql|convert to-myisam|convert to-innodb}"
       exit 1
  ;;
esac
