@echo off
cls
setlocal

rem Get release version of POM.
for /f "delims=" %%i in ('findstr /i /r ".*-SNAPSHOT" pom.xml') do (
  set VERSION="%%i"
)
rem Trim at left.
set VERSION=%VERSION:	<version>=%
rem Trim at right.
set VERSION=%VERSION:-SNAPSHOT</version>=%
rem Trim quotes.
set VERSION=%VERSION:"=%

rem Check version.
if %VERSION% == "" (
  echo [ERROR] No project version detected.
)

echo [INFO] Deploy version: %VERSION%

rem Name of git tag.
set TAGNAME=v%VERSION%

rem Remove old local tag.
call git tag -d "%TAGNAME%" 2>nul

rem Remove old remote tag.
call git push origin --delete "%TAGNAME%" 2>nul

rem Prepare a release without push remote tag and changes.
call mvn release:prepare -DremoteTagging=false -DpushChanges=false -Prelease-sign-artifacts
if %ERRORLEVEL% neq 0 goto ExitOnError

rem Push remote tag and changes.
call git commit -a -m "Prepare a release" 2>nul
call git tag "%TAGNAME%" 2>nul
call git push
if %ERRORLEVEL% neq 0 goto ExitOnError

call git push --tags
if %ERRORLEVEL% neq 0 goto ExitOnError

call git push origin
if %ERRORLEVEL% neq 0 goto ExitOnError

rem Perform a release.
call mvn release:perform -Prelease-sign-artifacts
if %ERRORLEVEL% neq 0 goto ExitOnError

endlocal
echo [INFO] ------------------------------------------------------------------------
echo [INFO] DEPLOY SUCCESS
echo [INFO] ------------------------------------------------------------------------
echo [INFO] The deploy has been completed with success!
exit /b 0

rem This is a label for GOTO.
:ExitOnError
echo [INFO] Restoring all POM in the project to their pre-release state.
call mvn release:rollback
call mvn release:clean
echo [INFO] ------------------------------------------------------------------------
echo [INFO] DEPLOY FAILURE
echo [INFO] ------------------------------------------------------------------------
echo [ERROR]
echo [ERROR] The deploy of project has not been completed. See logs for details.
echo [ERROR]
exit /b 1
rem end of file