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

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

SCHEMA=../src/db/schema.sqlite

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 (-i DB_NAME)"
	exit 1
fi

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

rm -f $DB_OUT
sqlite3 $DB_OUT < $SCHEMA 

echo "Converting database"

mysqldump --user="$DB_USR" --password="$DB_PWD" --host="$DB_HOST" "$DB_IN" \
  --skip-opt --no-create-db --no-create-info --skip-extended-insert \
  --skip-disable-keys --skip-set-charset --skip-lock-tables \
| sed -r -e 's/^INSERT INTO `([^"]+)`/INSERT INTO "\1"/' -e '/^SET/d' \
| sqlite3 $DB_OUT

exit 0
