#!/usr/pkg/bin/bash
set -e

# This scipt converts a ODS 1.4.9 MySQL database to ODS 2.0. It assumes both
# old and new databases live on the same host and are accessable by the same 
# user.

SCHEMA=./schema.mysql

DB_IN=""
DB_OUT=""
DB_HOST="localhost"
DB_USR="test"
DB_PWD="test"

while getopts "i:o:h:u:p:" arg; do
	case $arg in
	i) DB_IN=$OPTARG ;;
	o) DB_OUT=$OPTARG ;;
	h) DB_HOST=$OPTARG ;;
	u) DB_USR=$OPTARG ;;
	p) DB_PWD=$OPTARG ;;
	*)
		echo "usage: "$0" -i DATABASE_1.4 -o DATABASE_2.0 [-h HOST] [-u USER] [-p PASSWORD]"
		exit 1
	;;
	esac
done

if [ -z $DB_IN ]; then
	echo "ERROR: No input database specified"
	exit 1
fi

if [ -z $DB_OUT ]; then
	echo "ERROR: No output database specified"
	exit 1
fi

DB_VERSION=`echo "SELECT version FROM dbadmin;" | mysql -u $DB_USR -p$DB_PWD -h $DB_HOST $DB_IN | tail -n 1`
if [ ! $DB_VERSION -eq 4 ]; then
    echo "ERROR: Old database (version $DB_VERSION). Please upgrade to version 4 before migration"
    exit 1
fi

# Look for zones without an active key.
Z=`mysql -u $DB_USR -p$DB_PWD -h $DB_HOST $DB_IN < find_problematic_zones.sql`	
if [[ $Z = *[![:space:]]* ]]; then
	echo "Found zones without an active KSK but with a ready KSK waiting for ds-seen. This can cause problem after the conversion if the DS was actually already uploaded. You are adviced to submit these DS records and issue a ds-seen command before continueing. If you know better, disable this check to continue."
	       echo "Zones: $Z"
	exit 2
fi

echo "Creating database $DB_OUT (as user $DB_USR)"
echo "CREATE DATABASE IF NOT EXISTS $DB_OUT;" | 
	mysql -u $DB_USR -p$DB_PWD -h $DB_HOST

echo "Creating tables in $DB_OUT (as user $DB_USR)"
mysql -u $DB_USR -p$DB_PWD -h $DB_HOST $DB_OUT < $SCHEMA

echo "Converting database"
sed "s/REMOTE/$DB_IN/g" mysql_convert.sql > TMP
mysql -u $DB_USR -p$DB_PWD -h $DB_HOST $DB_OUT < TMP
rm TMP
