#!/bin/ksh
#
#	dvinv version 5.0 02/28/2012
#	original author Scott Bartholoma, NWIS
#	This is OSW Scripts page version.
#       Refer questions to "gs-w osw scripts"
#
# Usage: See usage() function below
#
# History
#  10/15/2003 - initial coding - SDB
#  03/26/2007 - updated for NWIS 4.7 parameter_cd/parm_cd change - WJW
#  02/28/2012 - Modified for Oracle database. -SDB
#
############################## START OF FUNCTIONS ##############################
#
# Functions to perform the various types of retrievals
#
################################################################################

# function to display the usage information
usage()
{
    echo
    echo 'Usage: dvinv [-p] [-m parm_cd ] [-a agency_cd] [-z db_no] site_no site_no site_no . . .'
    echo
    echo '	if agency code (agency_cd) is missing will default to USGS'
    echo '	if database number (db_no) is missing will default to db01'
    echo '  -p if present will result in only primary DDs being inventoried.'
    echo '  -m if present will result in only DDs for the supplied parameter code being inventoried.'
    echo
    echo '  If no station numbers are supplied the entire database will be inventoried'
    echo
}

# function to get and verify a table name from the database
get_table_name()
{
    # Use tsql to get the table name suffix from the database and construct
    # the actual table name
    #
    # Use like this:
    #
    # get_table_name dd
    # ddtbl=${table_name}
    #
    lcDDLnm=`echo "${1}" | tr '[A-Z]' '[a-z]'`
    ucDDLnm=`echo "${1}" | tr '[a-z]' '[A-Z]'`
    ret_table_name=${lcDDLnm}`/usr/local/bin/tsql ${NWISDB} "select suffix_tx \
        from ${NWIS_SCHEMA}.master_table where ddl_nm='${ucDDLnm}_##' AND db_no='${db_no}'"`
    # Verify we actually got a table name
    if [ -z "${ret_table_name}" ] ; then
	echo
	echo **** Fatal error - no table name retrieved for ddl_nm ${ucDDLnm}'_##' database ${db_no}
	echo
	exit 7
    fi
    table_name="${NWIS_SCHEMA}.${ret_table_name}"
}

##############################  END OF FUNCTIONS  ##############################
#
# Process the arguments
while getopts pa:z:m: arg ; do
    case $arg in
	p) primary=$arg;;
	a) agency_cd_in=$OPTARG;;
	z) db_no=$OPTARG;;
	m) parm_cd=$OPTARG;;
	\?) usage
	exit 2;;
    esac
done
shift `expr $OPTIND - 1`

#
# default agency code to USGS
if [ -z "${agency_cd_in}" ] ; then
    agency_cd="USGS"
else
    #
    # convert agency code to upper case
    agency_cd=`echo "${agency_cd_in}" | tr '[a-z]' '[A-Z]'`
fi

#
# default database number to 1
if [ -z "${db_no}" ] ;     then
    db_no=01
fi

#
# Make database number 2 digits if needed
if [ `echo ${db_no} | wc -c` -lt 3 ] ;     then
    db_no=0${db_no}
fi

#
# Source the nwis environment
. /usr/opt/etc/nwis.profile

#
# Source the wrapper
. $NWISHOME/util/nwo_set_nwis_env

#
# Create query to set date format to get yyyy-mm-dd style dates
dtFormatQuery="alter session set NLS_DATE_FORMAT='YYYY-MM-DD'"

#
# Get table names
get_table_name sitefile
sitetbl=${table_name}

get_table_name loc
loctbl=${table_name}

get_table_name dd
ddtbl=${table_name}

get_table_name dv
dvtbl=${table_name}

get_table_name dv_data
dvdtbl=${table_name}

#
# Construct optional where clause if primary DDs only are selected
if [ "${primary}" = "p" ] ; then
    primDDwhere=" and dd.dd_official_fg='Y'"
else
    primDDwhere=" "
fi

#
# Construct optional where clause for specific parameter_Cd
if [ -z "${parm_cd}" ] ; then
    parmDDwhere=" "
else
    parmDDwhere=" and dd.parm_cd='${parm_cd}'"
fi

#
# Write rdb file headers
echo "Agency\tStation\tDD\tPrimary\tParm\tStat\tNdays\tFrom\tTo\tBegins\tEnds" >| /tmp/$$.dvinv
echo "6S\t15S\t4N\t7S\t5S\t5S\t8N\t12N\t12N\t12S\t12S" >> /tmp/$$.dvinv

if [ -z "$1" ] ; then
    #
    # No site numbers supplied, do entire database
    tsql $NWISDB "${dtFormatQuery}" "select s.agency_cd,s.site_no,dd.dd_nu,dd.dd_official_fg,dd.parm_cd,dv.stat_cd,count(dvd.dv_dt),min(dvd.dv_va),max(dvd.dv_va),min(dvd.dv_dt),max(dvd.dv_dt) from ${sitetbl} s, ${loctbl} l, ${ddtbl} dd, ${dvtbl} dv, ${dvdtbl} dvd where l.site_id=s.site_id and dd.loc_id=l.loc_id ${primDDwhere} ${parmDDwhere} and dv.dd_id=dd.dd_id and dvd.dv_id=dv.dv_id group by s.agency_cd,s.site_no,dd.dd_nu,dd.dd_official_fg,dd.parm_cd,dv.stat_cd order by s.agency_cd,s.site_no,dd.dd_nu,dd.parm_cd,dv.stat_cd" >> /tmp/$$.dvinv
else
#
# Loop through the sites on the argument list
    while [ ! -z "${1}" ] ; do
  #
  # Get the DV inventory information
      tsql $NWISDB "${dtFormatQuery}" "select s.agency_cd,s.site_no,dd.dd_nu,dd.dd_official_fg,dd.parm_cd,dv.stat_cd,count(dvd.dv_dt),min(dvd.dv_va),max(dvd.dv_va),min(dvd.dv_dt),max(dvd.dv_dt) from ${sitetbl} s, ${loctbl} l, ${ddtbl} dd, ${dvtbl} dv, ${dvdtbl} dvd where s.agency_cd='${agency_cd}' and s.site_no='${1}' and l.site_id=s.site_id and dd.loc_id=l.loc_id ${primDDwhere} ${parmDDwhere} and dv.dd_id=dd.dd_id and dvd.dv_id=dv.dv_id group by s.agency_cd,s.site_no,dd.dd_nu,dd.dd_official_fg,dd.parm_cd,dv.stat_cd order by s.agency_cd,s.site_no,dd.dd_nu,dd.parm_cd,dv.stat_cd" >> /tmp/$$.dvinv
      
    #
    # shift this site off the argument list
      shift 1
    done
fi

#
# Sort the results and table it
sorttbl Agency Station DD Stat Begins < /tmp/$$.dvinv | ptbl -p0 -l132

#
# Clean up
rm /tmp/$$.dvinv


