#!/bin/bash -e

: ${DBUser:=sysdba}
: ${DBPass:=sysdba}
DB="$PWD/gdb"

Auth="-user $DBUser -password $DBPass"

if [ ! -e "$DB" ]; then
    echo >&2 'file ./gdb not found, you can use a command like one of these to get it:'
    echo >&2 '  Method=scp-only dbtm-dump .'
    echo >&2 '  Method=gbak-only dbtm-dump .'
    exit 1
fi

# for verbose mode, run with V=v
v() {
    echo "$@" >&2
    "$@"
}

# this does not presently attempt to re-create the schema
# it also does not check whether the data has changed, which might save some time

trigger_switch() {
    <list/trigger cut -f1 | grep -v -i '^v_' | sed "s/.*/alter trigger & $1;/" | isql $Auth "$DB"
}

wipe_db() {
	<table-order tac | sed 's/.*/delete from &;/' | isql $Auth "$DB"
}

restore_dat() { (
    cd dat
	dbidump -A -u "$DBUser" -p "$DBPass" -d 'dbi:InterBase:database=_;host=localhost;ib_dialect=3' restore "$DB" -t `<../table-order tr 'a-z' 'A-Z'` || true
) }

restore_gen() {
	<gen sed 's/^/set generator /; s/\t/ to /; s/$/;/' | isql $Auth "$DB" || true
}

$V trigger_switch inactive
$V wipe_db
$V restore_dat
$V restore_gen
$V trigger_switch active
