@echo off
echo ## I'm testing to see if the following files exist in the upload directory, "Gemfile, Rakefile, and public\404.html".. if they don't then the script won't do anything.

IF NOT EXIST upload\Gemfile GOTO ERROR
IF NOT EXIST upload\Rakefile GOTO ERROR
IF NOT EXIST upload\public\404.html GOTO ERROR
GOTO START

:ERROR
echo ## The upload directory does not contain project files!
GOTO END

:START
echo ## Stopping services... (cmiRails and Apache2.2)
echo ##
net stop cmiRails > nul
net stop Apache2.2 > nul

CD D:\InetPub

for /f "tokens=2-4 delims=/ " %%a in ('date /T') do set year=%%c
for /f "tokens=2-4 delims=/ " %%a in ('date /T') do set month=%%a
for /f "tokens=2-4 delims=/ " %%a in ('date /T') do set day=%%b
set DATE=%year%%month%%day%

for /f "tokens=1 delims=: " %%h in ('time /T') do set hour=%%h
for /f "tokens=2 delims=: " %%m in ('time /T') do set minutes=%%m
for /f "tokens=3 delims=: " %%a in ('time /T') do set ampm=%%a
set TIME=%hour%%minutes%

set NOW=%DATE%%TIME%

rem Move current directory to cmi-old-%NOW%
rem %NOW% is in the format of YYYYMMDDHHMM

MOVE cmi cmi-old-%NOW% > nul
echo ## I renamed the current folder to cmi-old-%NOW%

MOVE upload cmi > nul
echo ## I moved files from the upload folder to the cmi folder

rem Create upload directory again for the devs to upload the next release in to.
MKDIR upload

rem we want to keep the database.yml so grab a copy from the static directory and copy it to the newest release
COPY /Y static\database.yml cmi\config\database.yml > nul

echo ## I copied database.yml from the static fodler back in to the cmi\config folder
echo ##

rem Keep the last 3 old releases

set /A total_cnt=0
set /A remove_cnt=0

for /f %%A in ('DIR /OD /B cmi-old*') do set /a total_cnt+=1

IF %total_cnt% LEQ 3 goto STOP

set /A remove_cnt=%total_cnt%-3

echo ## There are %total_cnt% old releases, I removed %remove_cnt% release(s) because we want to keep the last 3 old releases.

setlocal ENABLEDELAYEDEXPANSION
set /A temp_cnt=1

for /f %%B in ('DIR /OD /B cmi-old*') do (
IF !temp_cnt! LEQ %remove_cnt% (
echo Deleting directory %%B...
rd /s /q %%B
)
set /A temp_cnt=temp_cnt+1
)
GOTO END
:STOP
echo ## There are %total_cnt% old release(s), I have not removed any because we want to keep the last 3 old releases.

echo ##
echo ## Starting services back up... (cmiRails, Apache2.2)
echo ##

net start cmiRails > nul
net start Apache2.2 > nul
:END