#!/bin/sh
#
# Retrieve RESURS DK-1 TLE spanning from 14th June 2006 till today
#
# Author Nico De Simone 2006/10/12 
#
# Modified by Emiliano Mocchiutti 2006/10/17
#

USER=pam2006
PASS=Resurs05
OUTFILE=tle.txt
FORCE="no"


if [ $# -gt 0 ]; then
    for INPUT in $*; do 
	if [ $INPUT == "--help" ] || [ $INPUT == "-h" ]; then
	    echo ""
	    echo " Usage: ./retrieve_TLE.sh [options] "
	    echo ""
	    echo " Options: "
	    echo ""
	    echo " --user=username : spacetrack username [default pam2006] "
	    echo ""
	    echo " --psw=password :  spacetrack password [default Resurs150606]"
	    echo ""
	    echo " --output=filename : output filename [default tle.txt]"
	    echo ""
	    echo " --force : override existing output file [default no]"
	    echo ""
	    # Check wget
	    if [[ -z `which wget` ]]; then
		echo "ERROR: please install wget to use this script!"
		exit 1
	    fi
	    exit 0
	fi
	TEST=`echo $INPUT | sed 's/--user=//g'`
	if [ $TEST != $INPUT  ]; then
	    USER=`echo $TEST`
	    export USER;
	fi
	TEST=`echo $INPUT | sed 's/--psw=//g'`
	if [ $TEST != $INPUT  ]; then
	    PASS=`echo $TEST`
	    export PASS;
	fi
	TEST=`echo $INPUT | sed 's/--output=//g'`
	if [ $TEST != $INPUT  ]; then
	    OUTFILE=`echo $TEST`
	    export OUTFILE;
	fi
	if [ $INPUT == "--force"  ]; then
	    FORCE="yes"
	    export FORCE;
	fi
    done
fi

# Check wget
if [[ -z `which wget` ]]; then
    echo "ERROR: please install wget to use this script!"
    exit 1
fi

if [ -f $OUTFILE ] && [ "$FORCE" == "no" ]; then
    echo ""
    echo " ERROR: TLE file $OUTFILE already exists (use --force)"
    echo ""
    exit 1
fi;

YEAR=`date +%Y`
MONTH=`date +%m`
DAY=`date +%d`

echo ""
echo " Today is $YEAR/$MONTH/$DAY"

echo ""
echo " Setting cookies to connect to spacetrack "
wget -o /dev/null -O /dev/null --save-cookies .cookies.txt \
http://www.space-track.org/perl/login.pl --post-data="_submitted=1&username=$USER&password=$PASS"
echo " Done!"
echo ""

echo " Retrieving Resurs-DK1 TLEs "
wget -o /dev/null -O - --load-cookies .cookies.txt \
--save-cookies .cookies.txt --keep-session-cookies \
http://www.space-track.org/perl/id_query.pl --post-data="_submitted=1&_sessionid=&ids=29228&timeframe=timespan&start_year=2006&start_month=6&start_day=14&end_year=$YEAR&end_month=$MONTH&end_day=$DAY&common_name=yes&sort=&descending=&ascii=yes&_submit=Submit&_reset=Reset" \
| egrep "1|2|R" > .tleretrieved.txt
echo " Done!"
echo ""

CHECK=`grep -i resurs .tleretrieved.txt `
if [[ `wc -l < .tleretrieved.txt` -le 2 ]] || [ "$CHECK" == "" ]; then # no tle
    echo "ERROR: No tle retrieved from spacetrack.org"
    echo ""
    rm -f .cookies.txt
    rm -f .tleretrieved.txt
    exit 1
fi

cp .tleretrieved.txt $OUTFILE

echo " File saved as $OUTFILE"
echo ""
rm -f .cookies.txt
rm -f .tleretrieved.txt
exit 0
