#! /bin/sh
#
# Name: cdbs_sql_gen.sh
#
# Description: Obtains a new CDBS delivery number (the next in sequence),
#              locks the delivery number, and generates a file of SQL
#              for loading the CDBS database from the content in the .lod
#              files for this delivery.  If SQL generation fails, the
#              lock entry is removed from the database for this new delivery
#              attempt.
#
# Called by:   deliver_cdbs.s
#
# Requires: env var CDBS_SERVER
#           env var CDBS_DB
#
# Returns: 0 - SQL generation succeeded
#          1 - failed to obtain DB lock or failure to generate SQL
#
#--------------------------------------------------------------------------
export CDBS_SERVER CDBS_DB
echo "starting cdbs_sql_gen"
echo "database " ${CDBS_DB?"CDBS_ERROR: CDBS_DB is undefined"}
echo "server " ${CDBS_SERVER?"CDBS_ERROR: CDBS_SERVER is undefined"}
date
#
# Determine the opus delivery number for the NEXT delivery 
#  (increments the last value)
#
delivery_number=`get_next_delivery_number.s | awk '/^ *[0-9]/{print $1}'`
echo "delivery_number = $delivery_number"
#
# lock the delivery in the database
lock_cdbs $delivery_number
if test $? -ne 0
then
 exit 1
fi
echo "load file(s)" *.lod
#
# generate the file of SQL for loading the CDBS database from this delivery's
#   .lod file content
#
cdbs_sql_gen *.lod
if test $? -ne 0
then
   # SQL generation failed, unlock the delivery in the database
   unlock_cdbs 
   exit 1
fi
exit 0
