#!/bin/bash

# getp48p [-d [[YYYY]-MM]-DD] {-h} 
# download pointing data file for P48 
#-----------------------------------------------------------------------
YMD=$(date +%Y-%m-%d); HELP=
#-----------------------------------------------------------------------
while getopts d:h OPTVAL
do
    case $OPTVAL in
	d) YMD=$OPTARG;;
	h) HELP=1;;
    esac
done
shift $((OPTIND-1))

if [ $HELP ]; then
    printf "\tgetp48p [-d DATE] {-h}\n" 
    printf "\tdownloads P48 pointing data for DATE from SkyVision\n"
    printf "\t-d .. starting date YYYY-MM-DD, default: today\n"
    printf "\tif MM-DD or DD specified then YYYY,MM default to that of today\n"
    printf "\toutput file: PYYYY_MM_DD.csv\n"
    exit
fi

#-----------------------------------------------------------------------
# decode date range
#-----------------------------------------------------------------------

# if no date  is given then default to today 
	! [ $YMD ] && YMD=$(date +%Y-%m-%d)

n=$(($(echo $YMD | sed 's/[^-]//g' | wc -c)-1))

case $n in
			#only day is given
	0) DD=$(printf "%02d" $YMD);
	   YMD=$(date +%Y-%m-)$DD;; 
			#month and day are given	
	1) MMDD=$(echo $YMD | awk -F"-" '{printf ("%02d-%02d",$1,$2)}');
	   YMD=$(date +%Y-)$MMDD;;
esac

#-----------------------------------------------------------------------
# The Heavy Lift
#-----------------------------------------------------------------------

OF=$(echo $YMD | sed 's/-/_/g;s/^/P/;s/$/.csv/')
curl -s "http://skyvision.caltech.edu:88/get_pointing_data?obsdate=$YMD" -o $OF


n=$(($(wc -l < $OF)-1))
if [ $n -eq -1 ]; then
  printf "nada \n"; rm $OF; exit 1
else 
  printf "number of sources: %d\n" $n
fi
