@echo off
TITLE CPE download tool

SET CPEFILE=CPE.BIN

REM If script is executed from Garmin device, update CPE.BIN in correct path
IF EXIST "%~d0\Garmin\GPS\*" SET "CPEFILE=%~d0\Garmin\GPS\CPE.BIN"

REM Purge old CPE file
copy /b /y NUL "%CPEFILE%" >NUL 2>&1
echo.

REM Try to find cURL download tool
SET DOWNTOOL=curl.exe
IF EXIST "%SystemRoot%\System32\curl.exe" (
 SET "DOWNTOOL=%SystemRoot%\System32\curl.exe"
 goto USECURL
)
IF EXIST "%SystemRoot%\curl.exe" (
 SET "DOWNTOOL=%SystemRoot%\curl.exe"
 goto USECURL
)
IF EXIST "%~dp0curl.exe" (
 SET "DOWNTOOL=%~dp0curl.exe"
 goto USECURL
)
WHERE curl.exe >NUL 2>&1 && goto USECURL

REM Try to find Wget download tool
SET DOWNTOOL=wget.exe
IF EXIST "%SystemRoot%\System32\wget.exe" (
 SET "DOWNTOOL=%SystemRoot%\System32\wget.exe"
 goto USECURL
)
IF EXIST "%SystemRoot%\wget.exe" (
 SET "DOWNTOOL=%SystemRoot%\wget.exe"
 goto USECURL
)
IF EXIST "%~dp0wget.exe" (
 SET "DOWNTOOL=%~dp0wget.exe"
 goto USEWGET
)
WHERE wget.exe >NUL 2>&1 && goto USEWGET

echo Error!
echo.
echo Cannot find cURL or Wget tool which are used for downloading ephmeris data.
echo.
echo Please download:
echo cURL from     https://curl.se/windows/
echo or Wget from  https://eternallybored.org/misc/wget/
goto END

:USEWGET
echo Fetching ephemeris data from Garmin with Wget tool...
"%DOWNTOOL%" --no-check-certificate --max-redirect=2 --tries=1 --timeout=10 -qO "%CPEFILE%" "https://api.gcs.garmin.com/ephemeris/cpe/broadcom?coverage=WEEKS_1"
goto SKIPCURL

:USECURL
echo Fetching ephemeris data from Garmin with cURL tool...
"%DOWNTOOL%" -k -s -o "%CPEFILE%" --max-redirs 2 -m 10 --max-filesize 500000 "https://api.gcs.garmin.com/ephemeris/cpe/broadcom?coverage=WEEKS_1"

:SKIPCURL

if NOT EXIST "%CPEFILE%" (
 echo.
 echo Error!
 echo.
 echo Cannot download CPE data from Garmin servers!
 goto END
)

SET CPESIZE=0
FOR %%F IN ("%CPEFILE%") DO SET "CPESIZE=%%~zF"
IF "%CPESIZE%"=="" SET CPESIZE=0

IF %CPESIZE% LSS 250000 (
 del /q /f "%CPEFILE%" >NUL 2>&1
 echo.
 echo Error!
 echo.
 echo Cannot download CPE data from Garmin servers!
 goto END
)

echo.
echo DONE!
echo.
echo Updated file "%CPEFILE%" now contains 7 days of fresh CPE data.
echo.

:END
SET CPEFILE=
SET DOWNTOOL=
SET CPESIZE=
echo.
ECHO Press any key to continue...
TIMEOUT /T 10 >nul
