#!/bin/sh

exec_sql()
{
if [ $# -ne 2 ]
    then
    echo "Programing error!"
    exit 200
fi
mysql --defaults-file=/etc/mysql/debian.cnf -ss -n $1 <<STOP
$2
\q
STOP
if [ $? -ne 0 ] ; then  echo "SQL job FAILed ! user:$user " >&2
exit 131
fi
}

do_import()
{
idb=$1
ifile=$2
	exec_sql ${idb} "set autocommit=0; set unique_checks=0; set foreign_key_checks=0; set sql_log_bin=0; set global slow_query_log=0;
		source ${ifile}
		commit; set autocommit=1; set unique_checks=1; set foreign_key_checks=1; set sql_log_bin=1; set global slow_query_log=1;"
}

usage()
{
    echo "Usage: $0 [db] [dumpfile]"
}

if [ $# -ne 2 ]
then
usage
exit 7
fi

db=$1
FILE=$2

if [ -f $FILE ]; then
    echo "Importing to db: $db, file: $FILE"

	case $FILE in
	*.sql.gz )
		echo "Unzipping $FILE"
		TMPFILE=$(mktemp -p . 2>/dev/null)
		if [ $? -gt 0 ]; then
			echo "Can't create temp file -> creating in /tmp"
			TMPFILE=$(mktemp)
		fi
		if (gunzip -k -c $FILE > $TMPFILE); then
			if [ -f $TMPFILE ]; then
				do_import $db $TMPFILE
				rm $TMPFILE
			else
				echo "Unzip FAILED"
			fi
		else
			echo "Unzip FAILED"
			if [ -f $TMPFILE ]; then
				echo "Deleting temp file"
				rm $TMPFILE
			fi
		fi
		;;
	*)
		do_import $db $FILE
		;;
	esac
else
    echo "File not found: $2"
fi
