#!/bin/sh
set -e

# This scipt converts a ODS 1.4.9 Sqlite database to ODS 2.0.

SCHEMA=/usr/local/share/opendnssec/schema.sqlite

DB_IN=""
DB_OUT=""

while getopts "i:o:" arg; do
	case $arg in
	i) DB_IN=$OPTARG ;;
	o) DB_OUT=$OPTARG ;;
	*)
		echo "usage: "$0" -i <DATABASE_1.4> -o <DATABASE_2.0>"
		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=`sqlite3 $DB_IN "SELECT version FROM dbadmin;"`
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=`sqlite3 $DB_IN < /usr/local/share/opendnssec/migration/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
 
rm -f $DB_OUT
sqlite3 $DB_OUT < $SCHEMA 
echo "attach '$DB_IN' as REMOTE;" |
	cat - /usr/local/share/opendnssec/migration/migrate-sqlite.sql | sqlite3 $DB_OUT

