<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
	<Target Name="GetPaths">
		<GetFrameworkSdkPath>
			<Output TaskParameter="Path" PropertyName="FrameworkSdkPath" />
		</GetFrameworkSdkPath>
		<GetFrameworkPath>
			<Output TaskParameter="Path"  PropertyName="FrameworkPath" />
		</GetFrameworkPath>
	</Target>

	<Target Name="GetProjects">
      <!-- Get all the projects associated with the solution -->
      <!--<GetSolutionProjects Solution="$(CodeFolder)\$(SolutionName)">
         <Output TaskParameter="Output" ItemName="SolutionProjects" />
      </GetSolutionProjects>-->

      <!-- Filter out solution folders and non .csproj items -->
      <RegexMatch Input="@(SolutionProjects)" Expression=".[\.]csproj$">
         <Output TaskParameter="Output" ItemName="Projects"/>
      </RegexMatch>

      <!-- Add Code folder to all solution project paths -->
      <RegexReplace Input="@(Projects)" Expression="(RodaxSoftware.*)\\" Replacement="Code\$1\\" Count="-1">
         <Output  TaskParameter="Output" ItemName="CSProjects"/>
      </RegexReplace>

      <!-- Resolve the test projects -->
      <RegexMatch Input="@(CSProjects)" Expression=".[\.](Testing|UnitTest|IntegrationTest).*[\.]csproj$">
         <Output TaskParameter="Output" ItemName="TestProjects"/>
      </RegexMatch>

      <!-- Resolve the code projects -->
      <CreateItem Include="@(CSProjects)"
                  Exclude="@(TestProjects);
                           @(SqlProjects)">
         <Output TaskParameter="Include" ItemName="CodeProjects"/>
      </CreateItem>

      <Message Text="$(NEW_LINE)Resolved the following solution projects:" Importance="high" />
      <Message Text="CodeProjects:$(NEW_LINE)$(TAB)@(CodeProjects->'%(RelativeDir)%(FileName)%(Extension)', '$(NEW_LINE)$(TAB)')" Importance="high"/>
      <Message Text="TestProjects:$(NEW_LINE)$(TAB)@(TestProjects->'%(RelativeDir)%(FileName)%(Extension)', '$(NEW_LINE)$(TAB)')" Importance="high"/>
      <Message Text="SqlProjects:$(NEW_LINE)$(TAB)@(SqlProjects->'%(RecursiveDir)%(FileName)%(Extension)', '$(NEW_LINE)$(TAB)')" Importance="high"/>

   </Target>
   
    <Target Name="GetIterationNumber">
      <!-- Read the the iteration number file contents -->
      <ReadLinesFromFile File="$(IterationNumberFile)">
         <Output TaskParameter="Lines" ItemName="IterationNumberFileContents"/>
      </ReadLinesFromFile>

      <!-- Assign file contents to IterationNumber property -->
      <CreateProperty Value="@(IterationNumberFileContents->'%(Identity)')">
         <Output TaskParameter="Value" PropertyName="IterationNumber"/>
      </CreateProperty>
   </Target>

	<Target Name="GetRevisionNumber"> 
		<!-- Get the revision number of the local working copy --> 
		<SvnInfo LocalPath="$(MSBuildProjectDirectory)"> 
			<Output TaskParameter="Revision" PropertyName="Revision"/> 
		</SvnInfo> 
	</Target> 
	
  
    <Target Name="CleanSolution">
      <Message Text="Cleaning Solution Output"/>

      <!-- Create item collection of custom artifacts produced by the build -->
      <CreateItem Include=
                   "@(TestProjects->'%(RootDir)%(Directory)bin\$(Configuration)\*$(NUnitFile)');
                    @(TestProjects->'%(RootDir)%(Directory)bin\$(Configuration)\*$(LastTestRunSucceededFile)');
                    @(TestProjects->'%(RootDir)%(Directory)bin\$(Configuration)\*$(NCoverFile)');
                    @(TestProjects->'%(RootDir)%(Directory)bin\$(Configuration)\*$(NCoverLogFile)')">
         <Output TaskParameter="Include" ItemName="SolutionOutput" />
      </CreateItem>

      <!-- Delete all the solution created artifacts -->
      <Delete Files="@(SolutionOutput)"/>

      <!-- Change the default BuildTarget to include a Clean before a Build -->
      <CreateProperty Value="Clean;$(BuildTargets)">
         <Output TaskParameter="Value" PropertyName="BuildTargets"/>
      </CreateProperty>

   </Target>	


	<Target Name="CreateOutputPath">
		<MakeDir Directories="$(OutputPath)" Condition="!Exists('$(OutputPath)')"/>
	</Target>
   
  	<Target Name="SvnVerify"> 
		<Error Text="No UserName or Password for accessing the repository has been specified" Condition=" '$(SvnUsername)' == '' Or '$(SvnPassword)' == '' " /> 
		<Error Text="No SvnTrunkFolder has been specified" Condition=" '$(SvnTrunkFolder)' == '' "/> 
		<Error Text="No SvnLocalPath has been specified" Condition=" '$(SvnLocalPath)' == '' "/> 
	</Target>
	
	
	<Target Name="GetEnvironment" Condition=" '$(DeploymentBuild)' == 'true' ">
		<!-- Read the Environment file contents -->
		<ReadLinesFromFile File="$(EnvironmentFile)">
			<Output TaskParameter="Lines" ItemName="EnvironmentFileContents"/>
		</ReadLinesFromFile>
		<!-- Assign file contents to Environment property -->
		<CreateProperty Value="@(EnvironmentFileContents->'%(Identity)')">
			<Output TaskParameter="Value" PropertyName="Environment"/>
		</CreateProperty>
		<Message Text="Running build for Environment = $(Environment)" importance="high" />
	</Target>


	<Target Name="Version"
           DependsOnTargets="GetIterationNumber;GetRevisionNumber" 
           Condition=" '$(DeploymentBuild)' == 'true' ">

      <!-- Assign IterationNumber to the Build property -->
      <CreateProperty Value="$(IterationNumber)">
         <Output TaskParameter="Value" PropertyName="Build"/>
      </CreateProperty>

      <!-- Add 1 to the Revision for the VersionInfo update commit -->
      <Add Numbers="$(Revision);1">
         <Output TaskParameter="Result" PropertyName="Revision"/>
      </Add>

      <CreateProperty Value="$(Major).$(Minor).$(Build).$(Revision)">
         <Output TaskParameter="Value" PropertyName="AppVersion"/>
      </CreateProperty>

      <Message Text="AppVersion number generated: $(AppVersion)" Importance="high"/>
     
      <!-- Generate the GlobalAssemblyInfo.cs file -->
      <AssemblyInfo CodeLanguage="CS"
           OutputFile="$(CodeFolder)\GlobalAssemblyInfo.cs"
           AssemblyConfiguration="$(Configuration)"
           AssemblyCompany="Sanlam Ltd"
           AssemblyProduct="MatrixQuote"
           AssemblyCopyright="Copyright (c) 2006-2007 Sanlam Ltd"
           AssemblyTrademark=""
           AssemblyCulture=""
           CLSCompliant="true"
           AssemblyVersion="$(AppVersion)"
           AssemblyFileVersion="$(AppVersion)" />
   </Target>
   
	<Target Name="BackupDatabase" Condition=" '$(DeploymentBuild)' == 'true' ">
		<Error Text="No DBBackupFolder has been specified" Condition="'$(DBBackupFolder)' == ''" />
		<Exec Command="$(DOUBLE_QUOTES)$(DBBackupScript)$(DOUBLE_QUOTES) $(SqlCmdRunner) $(DBServer)"
			WorkingDirectory="$(SqlScriptsFolder)"/>
		<CreateItem Include="$(DBBackupFolder)\SanQuote_*.bak">
			<Output TaskParameter="Include" ItemName="DBBackupFiles"/>
		</CreateItem>
	</Target>

	<Target Name="Sign" Condition=" '$(DeploymentBuild)' == 'true' ">
		<!-- Sign the assemblies -->
		<Exec Command="$(DOUBLE_QUOTES)$(FrameworkSdkPath)Bin\sn.exe$(DOUBLE_QUOTES) -Ra $(DOUBLE_QUOTES)%(CompiledAssemblies.FullPath)$(DOUBLE_QUOTES) $(KeyFile)"/>
	</Target>

  <Target Name="Package"
           DependsOnTargets="BackupDatabase"
           Condition=" '$(DeploymentBuild)' == 'true' ">

      <Error Text="No InstallShieldInputFolder has been specified" Condition="'$(InstallShieldInputFolder)' == ''" />
      <Error Text="No InstallShieldProjectFile has been specified" Condition="'$(InstallShieldProjectFile)' == ''" />

      <CreateItem Include=
                    "$(CodeOutputFolder)\**\*.*;
                     $(LibFolder)\*.*;"
                  Exclude=
                     "$(CodeOutputFolder)\*.cmd;
                      $(CodeOutputFolder)\*.$(NUnitFile);
                      $(CodeOutputFolder)\*.$(LastTestRunSucceededFile);
                      $(CodeOutputFolder)\*.$(FxCopFile);
                      $(CodeOutputFolder)\*.$(LastCodeAnalysisSucceededFile);
                      $(CodeOutputFolder)\*.$(NCoverFile);
                      $(CodeOutputFolder)\*.$(NCoverLogFile);                      
                      $(CodeOutputFolder)\Binding\**;
                      $(CodeOutputFolder)\Logs\**;
                      $(CodeOutputFolder)\Utilities\**;
                      $(CodeOutputFolder)\**\.svn\**;
                      $(LibFolder)\DevExpress*.xml;
                      $(LibFolder)\Sanlam.Core.xml;                      
                      $(LibFolder)\nunit*;
                      $(LibFolder)\TypeMock*;
                      $(LibFolder)\**\.svn\**">
         <Output TaskParameter="Include" ItemName="MsiFiles"/>
      </CreateItem>

      <CreateItem Include="$(InstallShieldInputFolder)\**\*.*">
         <Output TaskParameter="Include" ItemName="OldMsiFiles"/>
      </CreateItem>

      <Delete Files="@(OldMsiFiles)"/>

      <Copy SourceFiles="@(MsiFiles)"
            DestinationFiles="@(MsiFiles->'$(InstallShieldInputFolder)\%(RecursiveDir)%(FileName)%(Extension)')" />
      <Copy SourceFiles="@(DBBackupFiles)"
            DestinationFiles="@(DBBackupFiles->'$(InstallShieldInputFolder)\Database\%(RecursiveDir)%(FileName)%(Extension)')" />

      <!-- Set the version on the InstallShield Project -->
      <Exec Command="$(DOUBLE_QUOTES)$(SetMsiProductVersionScript)$(DOUBLE_QUOTES) $(DOUBLE_QUOTES)$(InstallShieldProjectFile)$(DOUBLE_QUOTES) $(AppVersion)"/> 

      <!-- Call InstallShield to create the msi -->
      <Exec Command="$(DOUBLE_QUOTES)$(InstallShieldCmd)$(DOUBLE_QUOTES) -p $(DOUBLE_QUOTES)$(InstallShieldProjectFile)$(DOUBLE_QUOTES) -o $(DOUBLE_QUOTES)$(InstallShieldMergeModulesFolder)$(DOUBLE_QUOTES) -t $(DOUBLE_QUOTES)$(FrameworkPath)$(DOUBLE_QUOTES) -b $(DOUBLE_QUOTES)$(InstallShieldOutputFolder)$(DOUBLE_QUOTES)" />
            
      <CreateItem Include="$(InstallShieldOutputFolder)\$(InstallShieldBuildFolders)\$(MsiInstallFile)">
         <Output TaskParameter="Include" ItemName="MsiInstallFileFullPath"/>
      </CreateItem>            
   </Target>	


	<Target Name="Deploy" Condition=" '$(DeploymentBuild)' == 'true' ">
		<Error Text="No DeploymentFolder has been specified" Condition=" '$(DeploymentFolder)' == ''" />
		<CreateProperty Value="$(DeploymentFolder)\$(AppVersion)">
			<Output TaskParameter="Value" PropertyName="InstallFolder"/>
		</CreateProperty>
		<Message Text="Install file: $(InstallFolder)\$(MsiInstallFile)" Importance="high" />
		<Copy SourceFiles="@(MsiInstallFileFullPath)" 
			DestinationFolder="$(InstallFolder)"/>
		
		<!-- Copy the msi onto the Qtp machine for regression testing -->
		<Copy SourceFiles="@(MsiInstallFileFullPath)" DestinationFolder="$(QtpInstallFolder)"/>
		
		<!-- Create the tokens for the InstallBuildEmail template -->
		<CreateItem Include="AppVersion" AdditionalMetadata="ReplacementValue=$(AppVersion)">
			<Output TaskParameter="Include" ItemName="EmailTokens"/>
		</CreateItem>
		<CreateItem Include="InstallFileFullPath" AdditionalMetadata="ReplacementValue=$(InstallFolder)\$(MsiInstallFile)">
			<Output TaskParameter="Include" ItemName="EmailTokens"/>
		</CreateItem>
		
		<!-- Create the InstallBuildEmail by replacing the tokens in the template file -->
		<TemplateFile Template="$(InstallBuildEmailTemplate)" OutputFilename="$(InstallBuildEmailFile)" Tokens="@(EmailTokens)" />
		<ReadLinesFromFile File="$(InstallBuildEmailFile)"> 
			<Output TaskParameter="Lines" ItemName="EmailBody"/> 
		</ReadLinesFromFile> 
		
		<!-- Send e-mail notification of the new build --> 
		<Mail SmtpServer="$(SmtpServer)" 
			To="@(Developers);@(QTPTesters)"
			Priority="High" 
			IsBodyHtml="true" 
			From="$(CCNetProject)@sanlam.co.za"
			Subject="Build $(AppVersion) ready for testing."
			Body="@(EmailBody)" />
	</Target>
	
	
  <Target Name="TagRepository"
           DependsOnTargets="SvnVerify;Version"
           Condition=" '$(DeploymentBuild)' == 'true' ">

      <!-- Increment the iteration number before the commit -->
      <Add Numbers="$(IterationNumber);1">
         <Output TaskParameter="Result" PropertyName="NextIterationNumber"/>
      </Add>

      <!-- Write out new iteration number to disk -->
      <WriteLinesToFile File="$(IterationNumberFile)"
                        Lines="$(NextIterationNumber)"
                        Overwrite="true"/>

      <!-- Commit all build changes -->

      <CreateProperty Value="Automatic commit of version info updates for the deployment build of iteration $(IterationNumber).">
         <Output TaskParameter="Value" PropertyName="SvnCommitMessage"/>
      </CreateProperty>

      <!-- Use svn directly as the SvnCommit task from MSBuildCommunityTasks requires Targets property to be set -->
      <Exec Command="$(DOUBLE_QUOTES)$(SubversionCmd)$(DOUBLE_QUOTES) commit $(DOUBLE_QUOTES)$(SvnLocalPath)$(DOUBLE_QUOTES) --username $(SvnUsername) --password $(SvnPassword) --message $(DOUBLE_QUOTES)$(SvnCommitMessage)$(DOUBLE_QUOTES)"/>
      
      <Message Text="Version Info changes commited at Revision: $(Revision)" Importance="high" />      
      
      <!-- Tag the repository on a successful build -->
      <SvnCopy SourcePath="$(SvnTrunkFolder)"
               DestinationPath="$(SvnTagsFolder)/Build-$(AppVersion)"
               Message="Automatic tag of successful deployment build for iteration $(IterationNumber)." />      

      <Message Text="Tag created at $(SvnTagsFolder)/Build-$(AppVersion)"  Importance="high"/>

   </Target>	
   
</Project>	