#!/bin/sh

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

#
# If not found Garmin/GPS folder, use current directory
#
[ "$foundcpe" != "1" ] && proccpe=CPE.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 CPE file
cp /dev/null "$proccpe" >/dev/null 2>&1

# Remove partially downloaded file in case of script premature exit
on_preExit() {
 test -f "$proccpe" && [ 0`wc -c<"$proccpe"|tr -cd '[:digit:]'` -lt 250000 ] && rm -f "$proccpe" >/dev/null 2>&1
 exit 2
}

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


echo Fetching ephemeris data from Garmin...
curl -k -s -o "$proccpe" --max-redirs 2 -m 10 --max-filesize 500000 'https://api.gcs.garmin.com/ephemeris/cpe/broadcom?coverage=WEEKS_1'

if [ ! -f "$proccpe" ]; then
 echo
 echo Error!
 echo Cannot download CPE data from Garmin servers!
 echo
 exit 1
fi

if [ 0`wc -c<"$proccpe"|tr -cd '[:digit:]'` -lt 250000 ]; then
 rm -f "$proccpe" >/dev/null 2>&1
 echo
 echo Error!
 echo Cannot download CPE data from Garmin servers!
 echo
 exit 1
fi

echo Done!
echo
echo Updated file \""$proccpe"\" now contains 7 days of fresh CPE data.
echo
exit 0
