#!/usr/bin/ksh

#
## list_l1_asf_cdfs.ksh - scripts creates files listing
## dates for which asf cdfs have been created. The ast
## cdf files are stored at:
##
##  /disks/themisdata/thg/l1/asi
##
##  thg_l1_asf[site]_[yyyymmdd]_vnn.cdf
##  example: thg_l1_asf_atha_20090201_v01.cdf
##
## Inputs:
## $1 = yyyy (4 digit year)
## $2 = mm (2 digit month)
## $3 = site (atha,whit,etc.)
##
#

## Set the environment variables
#
  if [[ -z $THMSOC ]]
	then
		THMSOC=/disks/socware/thmsoc_dp_current
		export THMSOC
	fi
#	. ${THMSOC}/src/config/soc_it_to_me.config
#  . ${THMSOC}/src/config/ground_asi.config

. /home/thmsoc/astraea2_test/soc_it_to_me.config
. /home/thmsoc/astraea2_test/ground_asi.config


## Check if arguments passed
#
  thisYear=$1
	thisMonth=$2
	oneSite=$3
	if [[ -z $thisYear ]]
	then
	  thisYear=$(date -u '+%Y')
	  thisMonth=$(date -u '+%m')
	fi

	if [[ -z $thisMonth ]]
	then
	  echo Please pas 2 digit month also
	  exit 1
	fi

	integer ithisMonth=$thisMonth
	integer ilastMonth=$(( ithisMonth - 1 ))

	if (( $ilastMonth <= 0 ))
	then
		lastMonth=12
		lastYear=$(( $thisYear - 1 ))
	else
		lastYear=$thisYear
		lastMonth=$(echo $ilastMonth | awk '{printf("%02d",$1)}')
	fi

	thisYearMonth=${thisYear}${thisMonth}
	lastYearMonth=${lastYear}${lastMonth}

## Process sites
#
	for yearMonth in $thisYearMonth $lastYearMonth
	do
		year=$(echo $yearMonth | awk '{print substr($1,1,4)}')
		month=$(echo $yearMonth | awk '{print substr($1,5,2)}')
		if [[ -z $oneSite ]]
		then
			for line in $(cat ${CONFIGDIR}/lc_asi_site_list.txt)
			do
				site=$(echo $line | awk '{print $1}')
				find ${L1ASIDIR}/${site}/${year}/${month}/ -name thg_l1_asf\* -exec /bin/basename {} \; |sort |awk -F_ '{print $5}' >> ${LOCAL}/asf_l1_cdf_list_${site}_${yearMonth}.txt
				mv -f ${LOCAL}/asf_l1_cdf_list_${site}_${yearMonth}.txt ${FILELISTS}
			done
		else
			find ${L1ASIDIR}/${oneSite}/${year}/${month}/ -name thg_l1_asf\* -exec /bin/basename {} \; |sort |awk -F_ '{print $5}' >> ${LOCAL}/asf_l1_cdf_list_${oneSite}_${yearMonth}.txt
			mv -f ${LOCAL}/asf_l1_cdf_list_${oneSite}_${yearMonth}.txt ${FILELISTS}
		fi
	done

## Cleanup
#
	exit 0
