#!/bin/sh

#
# Download 7 days of EPO data
#
numofdays=7
#
# Above default settings may be ovewritten by calling the script with parameters:
#
# getEPO numofdays
#
#
if [ "X$1" != X ]; then
 daysparm=`echo "$1"|tr -cd '[:digit:]'`
 test -n "$daysparm" && numofdays=$daysparm
 # No more than 9 days is usable for Garmin handhelds and watches
 [ $numofdays -gt 9 ] && numofdays=9
 [ $numofdays -lt 1 ] && numofdays=1
fi

#
# Find Garmin/GPS folder to put EPO.BIN inside it
#
foundepo=0
procepo=`dirname "$0"`
for i in 1 2 3 4; do
 if [ -d "${procepo}/Garmin/GPS" ]; then
  procepo="${procepo}/Garmin/GPS/EPO.BIN"
  foundepo=1
  break
 fi
 procepo=`dirname "$procepo"`
done

#
# If not found Garmin/GPS folder, use current directory
#
[ "$foundepo" != "1" ] && procepo=EPO.BIN

if ! command -v curl >/dev/null 2>&1
then
 echo Error!
 echo
 echo curl tool not found!
 echo Please install curl first.
 echo
 exit 1
fi


# Purge old EPO file
cp /dev/null "$procepo" >/dev/null 2>&1

epolimit=$(( $numofdays * 9216 ))

# Remove partially downloaded file in case of script premature exit
on_preExit() {
 test -f "$procepo" && [ X`wc -c<"$procepo"` != "X$epolimit" ] && rm -f "$procepo" >/dev/null 2>&1
 exit 2
}

trap on_preExit HUP INT QUIT ABRT TERM   # 1 2 3 6 15


echo Fetching ephemeris data from MediaTek...
epoend=$(( $epolimit - 1 ))
curl -s -o "$procepo" -r "0-$epoend" --max-redirs 2 -m 10 'http://epodownload.mediatek.com/EPO.DAT'

if [ ! -f "$procepo" ]; then
 echo
 echo Error!
 echo Cannot download EPO data from MediaTek servers!
 echo
 exit 1
fi

if [ X`wc -c<"$procepo"` != "X$epolimit" ]; then
 rm -f "$procepo" >/dev/null 2>&1
 echo
 echo Error!
 echo Cannot download EPO data from MediaTek servers!
 echo
 exit 1
fi

echo Done!
echo
echo Updated file \""$procepo"\" now contains $numofdays days of fresh EPO data.
echo
exit 0
