#!/usr/bin/env bash
#
# Copyright 2008, Centova Technologies Inc.
#
# In versions of MySQL prior to v4.1, all databases/tables used the latin1
# character set.  From MySQL v4.1 and up, MySQL supports UTF-8.
#
# If you upgraded MySQL to v4.1 or better from an earlier version, MySQL may
# report "Illegal mix of collations" errors in Centova Cast.  This script
# will fully convert your tables to UTF-8 to resolve these messages.
#
# Note that this script should ONLY be used on MySQL v4.1; on earlier
# versions, the results are untested and may be undesirable.
#

CONFIGPHP=`dirname $0`/../system/config.php
DBNAME=`cat $CONFIGPHP | grep 'define(.DB_NAME' | awk -F "'" '{print $4}'`
DBUSER=`cat $CONFIGPHP | grep 'define(.DB_USER' | awk -F "'" '{print $4}'`
DBPASS=`cat $CONFIGPHP | grep 'define(.DB_PASS' | awk -F "'" '{print $4}'`
DBHOST=`cat $CONFIGPHP | grep 'define(.DB_HOST' | awk -F "'" '{print $4}'`

mysqldump --add-drop-table -u"${DBUSER}" -h"${DBHOST}" -p"${DBPASS}" ${DBNAME} > centovacast_backup.sql
[ $? -gt 0 ] && echo "mysqldump failed" && exit
cat centovacast_backup.sql | sed 's/latin1/utf8/g' > centovacast_utf8.sql
[ $? -gt 0 ] && echo "utf8 sed replacement failed" && exit
mysql -u"${DBUSER}" -h"${DBHOST}" -p"${DBPASS}" ${DBNAME} < centovacast_utf8.sql
[ $? -gt 0 ] && echo "database import failed" && exit

echo "Conversion appears to have been successful.  If you encounter problems and"
echo "need to revert to your old database, a backup has been saved in the file"
echo "centovacast_backup.sql which you can import using the 'mysql' utility or"
echo "with phpMyAdmin or similar."

