#!/bin/sh
check_error()
{
	if [ $1 -ne 0 ] 
	then
	echo "loader failure [$1]. Exiting\n"
	exit 1
fi

}

loadpass()
{
	    
  for object_file in ${LIST} 
  do
    echo `date` Loading ${object_file} 
    ${UNZIP1} ${object_file} | eval ${FILTER} | ./loader -L $1 -p ${PROPERTIES} -s ${SOURCE}
    check_error $?
  done
}

# number of passes to load the db
# 0  means do not load data (empty_db)
# 1 means single pass, 2 means 2-pass loading
NPASSES=$1
NPASSES=${NPASSES:?"Usage $0 npasses"}
set -x
echo "*******************"`date`"******************" 
echo "Creating tables\n" 
echo "Creating tables\n"

cd SQL; ./create.first-stage; cd ..

if [ $NPASSES -gt 1 ]
then 	
  echo `date`"\n"
  echo "Loading tables - I pass\n"

  loadpass 1 
  check_error $?
fi

echo `date`"\n" 
echo "Making indexes\n"

cd SQL; ./create.second-stage; cd ..

if [ $NPASSES -gt 1 ]
then 	
  echo `date`"\n"
  echo "Loading tables - II pass\n"

  loadpass 2
  check_error $?
fi

echo `date`"\n"
echo "Making more indexes\n"

cd SQL; ./create.third-stage; cd ..


if [ $NPASSES -eq 1 ]
then
  echo `date`"\n"
  echo "Loading tables \n"

  loadpass 0
  check_error $?	
fi

echo "Finished "`date`

