@echo off
setlocal

echo.
echo Crappystrano - the shit script which (sort of) deploys stuff
echo deploy.cmd staging^|live [branchpath]
echo.

set SVN_REPO=file:///c:/dev/deploy/repo
set PROJECT_NAME=TheNameOfTheProject

:setup
set DEPLOY_ENV=%1
if not "%2"=="" (SET SVN_TRUNK=branches/%2) else set SVN_TRUNK=trunk

rem we need this in the path
if not exist %windir%\zip.exe (echo put zip.exe in the path && copy vendor\zip.exe %windir%)
rem we really need this.
svn --version -q >nul 2>nul
if ERRORLEVEL 1 (echo FATAL ERROR: Subversion [svn.exe] is not installed or not in the path. && goto :EOF)

set APPLICATION_NAME=

:check-params
if "%DEPLOY_ENV%"=="staging" goto :deploy-that-thang
if "%DEPLOY_ENV%"=="live" goto :deploy-that-thang

if "%DEPLOY_ENV%"=="" (echo FATAL ERROR: Deployment enviroment must be staging or live. && goto :eof)

:deploy-that-thang
set APPLICATION_NAME=%PROJECT_NAME%-%DEPLOY_ENV%

echo.
echo About to make a release for "%PROJECT_NAME%" to the "%DEPLOY_ENV%" enviroment from: %SVN_TRUNK%
pause

rem get the date in yyyymmddhhmmssms
set TMP_TIME=%time::=%
set TMP_TIME=%tmp_time:.=%
rem replace spaces with 0 if time < 10am
set TMP_TIME=%tmp_time: =0%
SET RELEASE_TIME_STAMP=%date:~6%%date:~3,2%%date:~0,2%%TMP_TIME%

set BRANCH_NAME=%APPLICATION_NAME%-%RELEASE_TIME_STAMP%
SET TMP_EXPORT_PATH=%tmp%\%BRANCH_NAME%

echo SVN export /%SVN_TRUNK%/ to temp folder: %TMP_EXPORT_PATH% && echo.
svn export -q %SVN_REPO%/%SVN_TRUNK% %TMP_EXPORT_PATH%

if not exist "%TMP_EXPORT_PATH%\src\%PROJECT_NAME%.sln" (echo FATAL ERROR: Subversion could not export from repository. && goto :EOF)
echo Building/Zipping release. && echo.

pushd %TMP_EXPORT_PATH%
%windir%\Microsoft.NET\Framework\v2.0.50727\msbuild.exe /verbosity:quiet /nologo src\%PROJECT_NAME%.sln >build.log
if ERRORLEVEL 1 (echo FATAL ERROR: Build Failed && goto :eof)

rem rename the src\web dir to the release name - so we get a nice zip file.
move src\web src\%BRANCH_NAME%

pushd src\
zip -m -r -q %BRANCH_NAME%.zip %BRANCH_NAME%
popd
popd

move %TMP_EXPORT_PATH%\src\%BRANCH_NAME%.zip . >nul
if exist %TMP_EXPORT_PATH% rd /s/q %TMP_EXPORT_PATH%

echo Branching SVN to  /tags/%BRANCH_NAME%
svn copy %SVN_REPO%/%SVN_TRUNK% %SVN_REPO%/tags/%DEPLOY_ENV%-%RELEASE_TIME_STAMP% -m "Crappystrano release: %APPLICATION_NAME% from branch: %SVN_TRUNK%"