#! /bin/bash
# MSTOPSQL Copyright (2008) Gwyneth Morrison
# This script runs the three stages of the postgres conversion

if [ $# -lt 1 ]
then
	echo Usage $0 SOURCEFILE [TRACE/DEBUG]
	exit 1
fi

# Preprocess the MS scripts

mstopre $1 

# Backup the trig/tab/func files

cp funclist.db funclist.db.bak
cp triglist.db triglist.db.bak
cp tablist.db tablist.db.bak

# Process thru conversion program

mstopsql.py mstopsql.sql $2  >  x.sql

ERRORS=$?
grep WARN x.sql >> WARNINGS
if [ $ERRORS != '0' ]
then
	echo $ERRORS 'ERROR(S) found in conversion'
	cp funclist.db.bak funclist.db
	cp triglist.db.bak triglist.db
	cp tablist.db.bak tablist.db
	exit $ERRORS
fi

# Stop here if trace or debug selected

if [ "X$2" != "X" ] 
then
	echo Stopped for Trace/Debug mode  
	cp funclist.db.bak funclist.db
	cp triglist.db.bak triglist.db
	cp tablist.db.bak tablist.db
	exit
	exit
fi

# Pass the result to postgres

pcmd < x.sql > x2.sql
ERRORS=`grep '\<ERROR' x2.sql | wc -l` 
if [ $ERRORS != '0' ]
then
	echo $ERRORS 'ERROR(S) found in compilation'
	cp funclist.db.bak funclist.db
	cp triglist.db.bak triglist.db
	cp tablist.db.bak tablist.db
	exit $ERRORS
fi

# Execute the resulting stored proc

echo 'select msload()' | pcmd > x3.sql
ERRORS=`grep 'ERROR' x3.sql | wc -l` 
if [ $ERRORS != '0' ]
then
	echo $ERRORS 'ERROR(S) found in execution'
	cp funclist.db.bak funclist.db
	cp triglist.db.bak triglist.db
	cp tablist.db.bak tablist.db
	exit $ERRORS
fi
echo no ERRORS found
