@echo off
rem
rem make_header - a workaround to build NSIS version info header from
rem Makefile using different environments (Windows cmd or Unix-like sh)
rem still being more or less portable.
rem
rem This script tries to find any git command line utility on the system.
rem First, it looks at the predefined location of git.exe installed by
rem msysgit package available at http://code.google.com/p/msysgit/
rem If not found, it searches for git executables in the system PATH.
rem If also not found, then it gives up and no commit info will be available.
rem
rem Expected parameters:
rem   %1: repository source path
rem   %2: header file full path and name
rem

rem FIXME: we should have product version info somewhere else
set OUT_FILE=OpenPilotGCS-%%%%ad-%%%%h-install.exe
set PRODUCT_VERSION=0.0.0.0
set FILE_VERSION=%%%%ad %%BRANCH%%:%%%%h
set BUILD_DESCRIPTION=Built using %%ORIGIN%% as origin, branch %%BRANCH%%, commit %%%%H, committed %%%%ci

set REPO=%1
set HEADER=%2
if "%REPO%"   == "" goto NoRepo
if "%HEADER%" == "" goto NoHeader
goto OK

:NoRepo
:NoHeader
echo This script should be called from Makefile only
goto :eof

:Ok
rem Looking for git command line utility at the predefined msysgit location
rem first, and in the PATH last. Also note that we use call command which is
rem required if we execute a .cmd or .bat file instead of .exe

set GIT=%ProgramFiles%\Git\bin\git.exe
if exist "%GIT%" goto Found

for %%G in (git.exe) do set GIT=%%~$PATH:G
if exist "%GIT%" goto Found

for %%G in (git.cmd) do set GIT=%%~$PATH:G
if exist "%GIT%" goto Found

for %%G in (git.bat) do set GIT=%%~$PATH:G
if exist "%GIT%" goto Found

:NotFound
echo git not found, no version info available
goto :eof

:Found
echo Using "%GIT%" to extract version info from "%REPO%"...

rem Getting remote origin name
for /F "usebackq tokens=1-3" %%G in (`call "%GIT%" remote -v`) do (
    if "%%G" == "origin" if "%%I" == "(fetch)" set ORIGIN=%%H
)

rem Getting branch name
for /F "usebackq tokens=1,2" %%G in (`call "%GIT%" branch --no-color`) do (
    if "%%G" == "*" set BRANCH=%%H
)

rem Getting commit info
set OPTS=-1 --no-color --date=short
set OPTS=%OPTS% "--format=format:
set OPTS=%OPTS%;%%%%n
set OPTS=%OPTS%; AUTOGENERATED HEADER FILE%%%%n
set OPTS=%OPTS%;%%%%n
set OPTS=%OPTS%%%%%n
set OPTS=%OPTS%; Installer file name%%%%n
set OPTS=%OPTS%!define OUT_FILE \"%OUT_FILE%\"%%%%n
set OPTS=%OPTS%%%%%n
set OPTS=%OPTS%; Installer version info%%%%n
set OPTS=%OPTS%!define PRODUCT_VERSION \"%PRODUCT_VERSION%\"%%%%n
set OPTS=%OPTS%!define FILE_VERSION \"%FILE_VERSION%\"%%%%n
set OPTS=%OPTS%!define BUILD_DESCRIPTION \"%BUILD_DESCRIPTION%\"%%%%n"

pushd "%REPO%"
call "%GIT%" log %OPTS% >%HEADER%
popd
