#!/bin/ksh
#

#       stop_mean_stage_processing version 5.0
#       original author Scott Bartholoma, NWIS
#       This is OSW Scripts page version.
#       Refer questions to "gs-w osw scripts"

#*************************************************************
# Purpose: Stop processing of daily mean stage.
# Remove it from the processor and delete all DVs for the database
#*************************************************************


#    History:
#      
#       11/2010  version 1.0 - Initial version. Scott Bartholoma
#        6/2012  version 5.0 - Updated for NWIS 5.0, fixed some typos and other minor updates. SDB/WJW
version=5.0
#
#
############################## START OF FUNCTIONS ##############################
#
# Functions to perform the various types of retrievals
#
################################################################################

# 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}"
}

# function to show processors the DD is involved in
show_processors()
{
    echo ' '
    echo "Processors for site  ${agency_cd} ${site_no}, DD ${dd_nu}:"
    
    #
    # Write rdb file headers
    echo "procstation\tprocdd\tstation\tdd_nu\tparm\ttype\tinout\tstart_dt\tend_dt\ts" >| /tmp/$$.prlist
    echo "20S\t6N\t20S\t6N\t5S\t4S\t5S\t20S\t20S\t7S" >> /tmp/$$.prlist
    
    #
    # Loop through all processors this DD is involved in
    for proc in `tsql $NWISDB "select distinct dt.ts_comp_inst_id \
    from ${sitetbl} s, ${loctbl} l, ${ddtbl} d, ${ddtstbl} dt \
    where s.agency_cd='${agency_cd}' and s.site_no='${site_no}' and \
    l.site_id=s.site_id and d.loc_id=l.loc_id and d.dd_nu=${dd_nu} and \
    dt.dd_id=d.dd_id"`
      do
      tsql $NWISDB "${dtFormatQuery}" "select s1.agency_cd || s1.site_no, d1.dd_nu, \
        s2.agency_cd || s2.site_no,d2.dd_nu, d2.parm_cd,\
	t.ts_comp_inst_cd,dt.dd_ts_comp_inst_cd,\
	t.ts_comp_start_dt,t.ts_comp_end_dt,dts.stat_cd \
	from ${ddtstbl} dt, ${tcitbl} t, \
        ${ddtbl} d1, ${loctbl} l1, ${sitetbl} s1, \
        (${ddtbl} d2 left join ${dcitbl} dts on \
        dts.ts_comp_inst_id=${proc} and dts.dd_id=d2.dd_id), \
        ${loctbl} l2, ${sitetbl} s2 \
	where dt.ts_comp_inst_id=${proc} and \
	t.ts_comp_inst_id=dt.ts_comp_inst_id and \
	d1.dd_id=t.dd_id and l1.loc_id=d1.loc_id and s1.site_id=l1.site_id and \
	d2.dd_id=dt.dd_id and l2.loc_id=d2.loc_id and s2.site_id=l2.site_id" \
	  >> /tmp/$$.prlist
    done
    
    if [ "`cat /tmp/$$.prlist | wc -l`" -le 2 ] ; then
	echo "No processors for station ${agency_cd} ${site_no}, DD ${dd_nu}."
    else
    #
    # Sort the results and table it
	sorttbl procstation procdd start_dt -r inout station dd_nu s |
	group2row -l s -by procstation procdd start_dt inout station dd_nu -carry parm type end_dt -collect s  < /tmp/$$.prlist | ptbl -b0 -p0 -l240
    fi
    
    #
    # Clean up
    rm /tmp/$$.prlist
}

# show rows in DV tables the DD has
show_dv()
{
    #
    # count rows in DV tables
    echo 'table\tparm\tstat\tfrom\tto\tnumdv\tmindv\tmaxdv' >| /tmp/$$.stop_mean_stage.tmp
    echo '20S\t5S\t5S\tt4N\t4N\t12N\t12N\t12N' >> /tmp/$$.stop_mean_stage.tmp
    query="select '${dvdtbl}',d.parm_cd,dv.stat_cd,min(dv.dv_water_yr),max(dv.dv_water_yr),count(dvd.dv_va),min(dvd.dv_va),max(dvd.dv_va) from ${ddtbl} d, ${dvtbl} dv, ${dvdtbl} dvd where d.dd_id=${dd_id} and dv.dd_id=d.dd_id and dvd.dv_id=dv.dv_id group by d.parm_cd,dv.stat_cd order by d.parm_cd,dv.stat_cd"
    tsql ${NWISDB} "${query}" >> /tmp/$$.stop_mean_stage.tmp
    query="select '${dvftbl}',d.parm_cd,dv.stat_cd,min(dv.dv_water_yr),max(dv.dv_water_yr),count(dvf.dv_va),min(dvf.dv_va),max(dvf.dv_va) from ${ddtbl} d, ${dvtbl} dv, ${dvftbl} dvf where d.dd_id=${dd_id} and dv.dd_id=d.dd_id and dvf.dv_id=dv.dv_id group by d.parm_cd,dv.stat_cd order by d.parm_cd,dv.stat_cd"
    tsql ${NWISDB} "${query}" >> /tmp/$$.stop_mean_stage.tmp
    
    echo ' '
    echo "DV data found for site ${agency_cd} ${site_no}, DD ${dd_nu}:"
    ptbl -l132 -p0 < /tmp/$$.stop_mean_stage.tmp
    rm  /tmp/$$.stop_mean_stage.tmp
}

# function to display the usage
usage()
{
    echo "Version: $version"
    echo
    echo 'Usage: stop_mean_stage_processing [-z db_no] [-a agency_cd] -n site_no -d dd_nu '
    echo
    echo '     If -z is omitted it will default to database 1'
    echo '     If -a is omitted it will default to "USGS"'
    echo
}
############################### END OF FUNCTIONS ###############################

# Determine if user has access to do this
if [ ! "`whoami`" = "nwis" ]
then
     echo ""
     echo "You are running as `whoami`. "
     echo "This script needs to be run as user nwis."
     echo "Therefore you can not run this script."
     echo
     echo "EXITING....."
     echo
     exit 1
fi

#
# Process the arguments
while getopts z:a:n:d: arg
do
  case $arg in
      z) db_no=$OPTARG;;
      a) agency_cd=$OPTARG;;
      n) site_no=$OPTARG;;
      d) dd_nu=$OPTARG;;
     \?) usage
         exit 1;;
  esac
done
shift `expr $OPTIND - 1`

#
# Check for all required arguments present
if [ -z "${site_no}" ] || [ -z "${dd_nu}" ] ; then
    usage
    exit 1
fi

#
# default agency code to USGS
if [ -z "${agency_cd}" ] ; then
    agency_cd="USGS"
fi

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

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

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

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

#
# Query to date format
dtFormatQuery="alter session set NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'"

echo

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

get_table_name loc LOC
loctbl=${table_name}

get_table_name dd DD
ddtbl=${table_name}

get_table_name ts_comp_inst TS_COMP_INST
tcitbl=${table_name}

get_table_name dd_ts_comp_inst DD_TS_COMP_INST
ddtstbl=${table_name}

get_table_name dv_comp_inst DV_COMP_INST
dcitbl=${table_name}

get_table_name dv DV
dvtbl=${table_name}

get_table_name dv_data DV_DATA
dvdtbl=${table_name}

get_table_name dv_diff DV_DIFF
dvftbl=${table_name}

# check for DD validity
tsql ${NWISDB} "select d.dd_id, d.parm_cd from ${sitetbl} s, ${loctbl} l, ${ddtbl} d where s.agency_cd='${agency_cd}' and s.site_no='${site_no}' and l.site_id=s.site_id and d.loc_id=l.loc_id and d.dd_nu=${dd_nu}" | read dd_id dd_parm
if [ -z "${dd_parm}" ] ; then
    echo "DD ${agency_cd} ${site_no}, DD ${dd_nu} does not exist."
    echo
    exit 2
fi

if [ ! "${dd_parm}" = "00065" ] ; then
    echo "DD ${agency_cd} ${site_no}, DD ${dd_nu} is parm code ${dd_parm}, not 00065."
    echo
    exit 3
fi

#
# Show processors the DD is involved in
show_processors

#
# Show DV rows to be deleted
show_dv

#
# confirm continuation
echo
echo
echo "Mean daily stage will no longer be computed/stored stored in the processors shown above and all mean daily"
echo "stage values shown above will be removed."
echo
print "Do you want to continue? (Y/N CR=Y):"; read answer 
echo
echo
case $answer in
  n | N | no | NO | No | nO )
   ucanswer="N";;
  * )
   ucanswer="Y";;
esac

# ucanswer=`echo "${answer}" | tr '[a-z]' '[A-Z]' `

if [[ $ucanswer != "Y" ]]
 then
 echo 'Exiting, NO actions were performed in the DB...'
 exit 4
else
 echo 'Building sql commands and executing them to clean the data out of the DB...'
fi



#
# Build an SQL commands file to do the deletions
echo
echo "Generating SQL to remove daily mean stage from the proccessors and DV tables:"
echo "set echo on;" >| /tmp/$$.stop_mean_stage.sql
echo " " >> /tmp/$$.stop_mean_stage.sql
echo "delete from ${dcitbl} where dd_id=${dd_id} and stat_cd='00003';" >> /tmp/$$.stop_mean_stage.sql
echo " " >> /tmp/$$.stop_mean_stage.sql
echo "delete from ${dvftbl} where dv_id in (select dv_id from ${dvtbl} where dd_id=${dd_id} and stat_cd='00003');" >> /tmp/$$.stop_mean_stage.sql
echo " " >> /tmp/$$.stop_mean_stage.sql
echo "delete from ${dvdtbl} where dv_id in (select dv_id from ${dvtbl} where dd_id=${dd_id} and stat_cd='00003');" >> /tmp/$$.stop_mean_stage.sql
echo " " >> /tmp/$$.stop_mean_stage.sql
echo "delete from ${dvtbl} where dd_id=${dd_id} and stat_cd='00003';" >> /tmp/$$.stop_mean_stage.sql
echo " " >> /tmp/$$.stop_mean_stage.sql
echo "commit;" >> /tmp/$$.stop_mean_stage.sql
echo " " >> /tmp/$$.stop_mean_stage.sql
echo "quit" >> /tmp/$$.stop_mean_stage.sql

#
# Execute the SQL
echo
echo "Executing SQL to remove daily mean stage from the proccessors and DV tables:"
cat /tmp/$$.stop_mean_stage.sql
sqlplus /@${NWIS_HOST} @/tmp/$$.stop_mean_stage.sql

#
# clean up
rm /tmp/$$.stop_mean_stage.sql

#
# Show contents after the operation
echo
echo 'After deletes: '

#
# Show processors the DD is involved in
show_processors

#
# Show DV rows to be deleted
show_dv
