#!/bin/bash

# TESS
center='500@-95'

# Ceres
target='1'

observer=""
tstart=""
tend=""
tstep=""

while [ -n "$1" ]; do
    case "$1" in
	-h|--help)
		echo -e	"Usage:	$0 [-h|--help]"
		echo -e	"	[-b|--observer {tess|kepler|geocenter}]"
		echo -e "	-j|--object <object>"
		echo -e "	-t|--time|interval <T>|<Tmin>:<Tmax>|<Tmin>:<step>:<Tmax>"
		exit	0
		;;
	-b|--observer)
		observer="$2"
		shift
		;;
	-j|--object)
		target="$2"
		shift
		;;
	-t|--time|--interval)
		A=(${2//:/ })
		if [ ${#A[*]} -eq 1 ]; then
			tstart=${A[0]}
			tend=${A[0]}
			tstep="1 d"
		elif [ ${#A[*]} -eq 2 ]; then
			tstart=${A[0]}
			tend=${A[1]}
			tstep="1 d"
		else
			tstart=${A[0]}
			tstep=${A[1]}
			tend=${A[2]}
		fi
		shift
		;;
	*)
		echo "$0: error: invalid command line argument near '$1'." >> /dev/stderr
		exit	1
		;;
    esac
    shift
done

if [ -n "$observer" ]; then case "$observer" in
	tess)		center='500@-95';;
	kepler)		center='500@-227';;
	geocenter)	center='500';;
esac; fi

if ! [ -n "$tstart" ]; then
	echo "$0: warning: no time instance or interval defined, exiting." >> /dev/stderr
	exit	0
fi

# Interval & stepsize
JD_BEG=$tstart
if [ "$tstart" == "$tend" ]; then
	JD_END=`echo $JD_BEG | awk '{ printf("%.5f\n",$1+0.5); }'`
	D_STEP="1d"
else
	JD_END=$tend
	D_STEP=`echo $tstep | awk '{ printf("%d m",$1*1440); }'`
fi

URL="https://ssd.jpl.nasa.gov/horizons_batch.cgi?batch=1"
URL="${URL}&COMMAND='$target%3B'&CENTER='$center'&MAKE_EPHEM='YES'&TABLE_TYPE='OBSERVER'"
URL="${URL}&START_TIME='JD ${JD_BEG}'&STOP_TIME='JD ${JD_END}'&STEP_SIZE='${D_STEP}'"
URL="${URL}&QUANTITIES='1,9,19,20,23,24'&CAL_FORMAT='JD'&ANG_FORMAT='DEG'" 

wget --no-check-certificate -O - -q "${URL}" | \
awk -v print_line=0 \
 '{	if ( $1=="$$SOE" )
		print_line=1;
	else if ( $1=="$$EOE" )
		print_line=0;
	else if ( print_line )
		print;
 }'

# References: 
# ftp://ssd.jpl.nasa.gov/pub/ssd/horizons_batch_example.long
# https://ssd.jpl.nasa.gov/horizons_batch.cgi

