#!/bin/bash

twiggi_name=$1
twiggi_db=$2
twiggi_user=$3
twiggi_pw=$4
#twiggi_skript=/var/www/html/EdunixMail/install/linweb.sql
dbs="--host=$5"

if [ "$6" = "user" -a "$8" = "password" ] ; then
	user="-u$7"
	pw="-p$9"
else
	pw=""
	user="-uroot"
	mysqladmin $dbs version  2>&1 &> /dev/null
	needpw=$?;

	# if called from rpm install: $6=="rpm" 
	if [ "$6" = "rpm" -a "$needpw" = "1" ] ; then
		echo 
		echo "You must run the command the following command to update the database:"
		echo "/usr/local/bin/twiggi-db-setup"
		echo
		exit 0;
	fi

	if [ "$needpw" = "1" ] ; then
		echo
		echo "You must enter the MySQL password. The password can be found"
		echo "in the file '/etc/my.cnf on most systems. Occasionally it is"
		echo "identical with the root password."
		echo
	fi

	while [ "$needpw" = "1" ] ; do
		echo -n "MySQL password: " 
		read pw 
		if [ "$pw" = "" ] ; then
			echo "terminated."
			exit;
		fi
		mysqladmin $dbs $user -p$pw version  2>&1 &> /dev/null
		needpw=$?;
		if [ "$needpw" = "1" ] ; then
			echo "Access to MySQL server denied, please try again."
		fi
	done
fi

echo exit | mysql $dbs $user $pw $twiggi_db  2>&1 &> /dev/null
if [ "$?" = "1" ] ; then
	echo "Creating database $twiggi_db for $twiggi_name..."
	mysqladmin $dbs $user $pw create $twiggi_db
	echo "grant all on $twiggi_db.* to $twiggi_user@localhost identified by \"$twiggi_pw\";" | mysql $dbs $user $pw 
	mysql $dbs $user $pw $twiggi_db < twiggi.table.mysql
	mysqladmin $dbs $user $pw reload
fi

# upgrade
f=0
while true ; do
    db=`echo "SELECT dbversion from twiggi" | mysql $dbs $user $pw $twiggi_db | tail -1`
    ug="$db-twiggi.table.mysql";
    if [ -f "$ug" ] ; then
		if [ "$f" = "0" ] ; then
    		echo -n "upgrading $twiggi_db database ."
			f=1
		else
			echo -n "."
		fi
        mysql -f $dbs $user $pw $twiggi_db < "$ug"
    else
		echo ""
        break
    fi
done 

mdsum_cur=`echo "select name from twig_holiday_names where nid=0;" | mysql --silent $dbs $user $pw $twiggi_db`
mdsum_new=`cat holiday.md5sum`
if [ "$mdsum_cur" != "$mdsum_new" ] ; then
echo "updating holiday databases..."
mysql $dbs $user $pw $twiggi_db < holiday.db
fi;
