#!/bin/sh
#
# Name: run_delivery_sql
#
# Description: Runs the CDBS SQL file in the current directory for the
#              currently active deliveryNumber.
#
# Called by: sendit
#
# Requires: env var CDBS_SERVER
#           env var CDBS_DB
#
# Returns:  0 = no errors detected in SQL output
#           1 = error locating the SQL file or errors in the SQL output
#
#-----------------------------------------------------------------------
echo "starting run_delivery_sql"
echo "database " ${CDBS_DB?"CDBS_ERROR: CDBS_DB is undefined"}
echo "server " ${CDBS_SERVER?"CDBS_ERROR: CDBS_SERVER is undefined"}
date
#
dn=`get_current_delivery_number.s | awk '/^ *[0-9]/{print $1}'`
fin=cdbs_delivery$dn.sql
fout=$fin.out
echo $fout
if test -f $fin
then
  echo "using file $fin"
else
  echo "CDBS ERROR: file $fin does not exist"
  exit 1
fi
isql -S${CDBS_SERVER} -e < $fin  > $fout
if [ `grep '^Msg' $fin.out | wc -l` -gt 0 -o `grep -i "CDBS ERROR" $fin.out | wc -l` -gt 0 ]
then
   echo "possible errors in processing sql file $fin"
   echo "see output file $fout"
   exit 1
fi
if test -s $fout
then
   echo "no apparent errors in processing sql file $fin"
   echo "created output file $fout"
   exit 0
else
   echo "ERROR: EMPTY SQL output file $fout"
   echo "FAILED to apply CDBS SQL to the database."
   exit 1
fi
