<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildProjectDirectory)\Properties\template-builder.props" 
          Condition="Exists('$(MSBuildProjectDirectory)\Properties\template-builder.props')" />
  <!--
  1. Discover all .vstemplate files
  2. For each .vstemplate file, go up one folder and create a .zip from the content (exluding the _Definitions folder)
  -->

  <PropertyGroup>
    <!-- 
    Constants 
    -->
    <ls-BuildRoot Condition=" '$(ls-BuildRoot)'=='' ">$(MSBuildProjectDirectory)\Build\</ls-BuildRoot>
    <ls-TasksRoot Condition=" '$(ls-TasksRoot)'==''">$(MSBuildThisFileDirectory)</ls-TasksRoot>
    <ls-BuildLib Condition=" '$(ls-BuildLib)'=='' and Exists('$(MSBuildThisFileDirectory)\ligershark.templates.targets')">$(MSBuildThisFileDirectory)\</ls-BuildLib>
    <ls-BuildLib Condition=" '$(ls-BuildLib)'=='' ">$(ls-BuildRoot)Lib\</ls-BuildLib>
    
    <!-- 
    Item Templates 
    -->
    <ls-ItemTemplateRoot Condition=" '$(ls-ItemTemplateRoot)'=='' ">$(MSBuildProjectDirectory)\ItemTemplates\</ls-ItemTemplateRoot>
    <ls-ItemTemplateOutputRoot Condition=" '$(ls-ItemTemplateOutputRoot)'=='' ">$(IntermediateOutputPath)ls-ItemTemplates\</ls-ItemTemplateOutputRoot>
    
    <ls-ItemTemplatesExtendBuild Condition=" '$(ls-ItemTemplatesExtendBuild)'=='' ">true</ls-ItemTemplatesExtendBuild>
    <!-- This is where all the Item Template .zip files will be located -->
    <ls-ItemTemplateZipRootFolder Condition=" '$(ls-ItemTemplateZipRootFolder)'=='' ">Output\ItemTemplates\</ls-ItemTemplateZipRootFolder>
    
    <!--
    Project Templates
    -->
    <ls-ProjectTemplateRoot Condition=" '$(ls-ProjectTemplateRoot)'=='' ">$(MSBuildProjectDirectory)\ProjectTemplates\</ls-ProjectTemplateRoot>
    <ls-ProjectTemplateOutputRoot Condition=" '$(ls-ProjectTemplateOutputRoot)'=='' ">$(IntermediateOutputPath)ls-ProjectTemplates\</ls-ProjectTemplateOutputRoot>
    <!-- This is where all the Project Template .zip files will be located -->
    <ls-ProjectTemplateZipRootFolder Condition=" '$(ls-ProjectTemplateZipRootFolder)'=='' ">Output\ProjectTemplates\</ls-ProjectTemplateZipRootFolder>

    <ls-SnippetFolderRoot Condition=" '$(ls-SnippetFolderRoot)'=='' ">$(MSBuildProjectDirectory)\Snippets\</ls-SnippetFolderRoot>
    
    <!-- This is normally defined by the .props file imported above ( $(MSBuildProjectDirectory)\Properties\template-builder.props )-->
    <ls-TemplateSubFolder Condition=" '$(ls-TemplateSubFolder)'=='' ">Custom Templates</ls-TemplateSubFolder>
    
    <ls-MSBuildLibPathLocal Condition=" '$(ls-MSBuildLibPathLocal)'=='' ">$(LocalAppData)\Microsoft\MSBuild\TemplateBuilder\v1.0.0.0\</ls-MSBuildLibPathLocal>
    <ls-MSBuildLibPath Condition=" '$(ls-MSBuildLibPath)'=='' ">$(MSBuildThisFileDirectory)</ls-MSBuildLibPath>
  </PropertyGroup>
  
  <PropertyGroup>
    <ls-UseHardLinksForItemTemplatesCopy Condition=" '$(ls-UseHardLinksForItemTemplatesCopy)'=='' ">false</ls-UseHardLinksForItemTemplatesCopy>
  </PropertyGroup>

  <ItemGroup>
    <ls-BuildAssemblies Include="$(ls-MSBuildLibPath)*.dll"/>
  </ItemGroup>
  <Target Name="CopyMSBuildFilesToLocalAppData"
          Inputs="@(ls-BuildAssemblies)"
          Outputs="@(ls-BuildAssemblies->'$(ls-MSBuildLibPathLocal)%(FileName)%(Extension)')">
    
    <MakeDir Directories="$(ls-MSBuildLibPathLocal)"/>
    <Copy SourceFiles="@(ls-BuildAssemblies)"
          DestinationFiles="@(ls-BuildAssemblies->'$(ls-MSBuildLibPathLocal)%(FileName)%(Extension)')"
          Condition="!Exists('$(ls-MSBuildLibPathLocal)%(ls-BuildAssemblies.FileName)%(ls-BuildAssemblies.Extension)')"
          />
    
  </Target>

  <UsingTask AssemblyFile="$(ls-MSBuildLibPathLocal)MSBuild.ExtensionPack.dll" TaskName="MSBuild.ExtensionPack.Compression.Zip" />
  
  <!-- This hooks up the ItemTemplate targets to the Build Process -->
  <PropertyGroup>
    <CoreCompileDependsOn Condition=" '$(ls-ItemTemplatesExtendBuild)'=='true' ">
      CopyMSBuildFilesToLocalAppData;
      RemoveTemplateFilesFromCompile;
      IncludeSnippetFilesInVsix;
      $(CoreCompileDependsOn);
      ls-ProcessItemTemplates;
    </CoreCompileDependsOn>
  
    <ls-ProcessItemTemplatesDependsOn>
      $(ls-ProcessItemTemplatesDependsOn);
      ls-DiscoverItemTemplateFiles;
      ls-CreateZipForEachItemTemplate;
      ls-AddCreatedItemTemplateZipFilesToProject;
    </ls-ProcessItemTemplatesDependsOn>
  </PropertyGroup>

  <Target Name="RemoveTemplateFilesFromCompile" BeforeTargets="CoreCompile">
    <Message Text="Removing ItemTemplate and ProjectTemplate files from Compile list"/>

    <!-- Files under ItemTemplates and ProjectTemplates should not be included in the Compile list -->
    <ItemGroup>
      <Compile Remove="$(ls-ItemTemplateRoot)**\*"/>
      <Compile Remove="$(ls-ProjectTemplateRoot)**\*"/>

      <Compile Remove="ProjectTemplates\**\*"/>
      <Compile Remove="ItemTemplates\**\*"/>
    </ItemGroup>

    <Message Text="ls-ItemTemplateRoot:[$(ls-ItemTemplateRoot)]" Importance="low"/>
    <Message Text="ls-ProjectTemplateRoot:[$(ls-ProjectTemplateRoot)]" Importance="low"/>
  </Target>

  <Target Name="ls-ProcessItemTemplates" DependsOnTargets="$(ls-ProcessItemTemplatesDependsOn)" />
  
  <Target Name="ls-DiscoverItemTemplateFiles">
    <!-- Look through Item Templates folder for all .vstemplate files in the project (as Content) -->
    <ItemGroup>
      <!-- Item Templates -->
      <ls-VsTemplateFiles Include="$(ls-ItemTemplateRoot)**\*.vstemplate" Exclude="$(ls-ItemTemplateRoot)**\MyTemplate.vstemplate">
        <TemplatesRoot>$(ls-ItemTemplateRoot)</TemplatesRoot>
        <ZipRootFolder>$(ls-ItemTemplateZipRootFolder)</ZipRootFolder>
      </ls-VsTemplateFiles>
      
      <!-- Project Template -->
      <ls-VsTemplateFiles Include="$(ls-ProjectTemplateRoot)**\*.vstemplate" Exclude="$(ls-ProjectTemplateRoot)**\MyTemplate.vstemplate">
        <TemplatesRoot>$(ls-ProjectTemplateRoot)</TemplatesRoot>
        <ZipRootFolder>$(ls-ProjectTemplateZipRootFolder)</ZipRootFolder>
      </ls-VsTemplateFiles>
    </ItemGroup>

    <ItemGroup Condition=" '$(Configuration)'=='Release' " >
      <!-- If we are not building on release mode let's remove any item starting with _Sample -->
      <ls-IT-ToRemove Include="$(ls-ItemTemplateRoot)**\_Sample*\_Definitions\*.vstemplate" />
      <ls-PT-ToRemove Include="$(ls-ProjectTemplateRoot)**\_Sample*\_Definitions\*.vstemplate" />
      <ls-VsTemplateFiles Remove="@(ls-IT-ToRemove);@(ls-PT-ToRemove)" />
    </ItemGroup>
    <Message Text="Removed the following Sample templates from the VSIX because build is set to [$(Configuration)]. 
Item Templates: @(ls-IT-ToRemove)
Project Templates: @(ls-PT-ToRemove)" Importance="high"/>
    
    <Message Text="Vs Template Files found: @(ls-VsTemplateFiles,'%0a%0d')" />
  </Target>

  <PropertyGroup>
    <ls-CreateZipForEachItemTemplateDependsOn>
      $(ls-CreateZipForEachItemTemplateDependsOn);
      ls-DiscoverItemTemplateFiles;
      ls-InitalizeItemTemplateOutputFolder;
      ls-CalculateItemGroupOutputsForItemTemplates;
      ls-CopyTemplateFilesToIntermediateFolder;
      ls-PreprocessTemplates;
    </ls-CreateZipForEachItemTemplateDependsOn>
  </PropertyGroup>

  <PropertyGroup>
    <ls-CopyTemplateFilesToIntermediateFolderDependsOn>
      $(ls-CopyTemplateFilesToIntermediateFolderDependsOn);      
    </ls-CopyTemplateFilesToIntermediateFolderDependsOn>
  </PropertyGroup>
  <!-- This target will run once per value in @(ls-ItemTemplatesOutputs) -->
  <Target Name="ls-CopyTemplateFilesToIntermediateFolder"
          Inputs="%(_ls-ItemTemplatesOutputs.VsTemplateSourcePath)" 
          Outputs="%(_ls-ItemTemplatesOutputs.Identity);All"
          DependsOnTargets="$(ls-CopyTemplateFilesToIntermediateFolderDependsOn)">
    <Message Text="Determining files to incude in Item Template .zip file for [%(_ls-ItemTemplatesOutputs.VsTemplateSourcePath)]"/>

    <!-- 
    Grab all the files from the folder (excluding any .vstemplate file and any files under _Definitions\)
    and create a .zip file from it in the output folder.    
    -->
    <ItemGroup>
      <_ls-ItemsToZip Remove="@(_ls-ItemsToZip)"/>
      <_ls-ItemsToZip Include="%(_ls-ItemTemplatesOutputs.ItemTemplateFolder)**\*" />
      <!-- <_ls-ItemsToZip Include="%(_ls-ItemTemplatesOutputs.ItemTemplateFolder)**\*" 
                      Exclude="%(_ls-ItemTemplatesOutputs.ItemTemplateFolder)_Definitions\**\*;%(_ls-ItemTemplatesOutputs.ItemTemplateFolder)**\*.vstemplate"> 
      </_ls-ItemsToZip>-->
    </ItemGroup>

    <Message Text="Creating Item Template .zip file at [%(_ls-ItemTemplatesOutputs.OutputPathWithFileName)]" />
    
    <!-- We need to copy the files into a subfolder under obj\ and then create the .zip file from that -->
    <PropertyGroup>
      <_ls-IntermediateItemTemplateFolder>$(ls-ItemTemplateOutputRoot)%(_ls-ItemTemplatesOutputs.ItemTemplateName)\</_ls-IntermediateItemTemplateFolder>
    </PropertyGroup>

    <!-- delete the old content and copy it over from the source -->
    <ItemGroup>
      <_ls-FilesToDelete Remove="@(_ls-FilesToDelete)"/>
      <_ls-FilesToDelete Include="$(_ls-IntermediateItemTemplateFolder)"/>
    </ItemGroup>
    <Delete Files="@(_ls-FilesToDelete)" />   
    <MakeDir Directories="$(_ls-IntermediateItemTemplateFolder)"/>

    <ItemGroup>
      <ls-temp-FilesCopied Remove="@(ls-temp-FilesCopied)" />
    </ItemGroup>

    <!-- TODO: This needs to be refactored into its own target -->
    <!-- Copy over the .vstemplate to the root folder and then copy all files -->
    <Copy SourceFiles="%(_ls-ItemTemplatesOutputs.VsTemplateSourcePath)"
          DestinationFiles="$(_ls-IntermediateItemTemplateFolder)%(_ls-ItemTemplatesOutputs.Filename).vstemplate">
      <Output TaskParameter ="CopiedFiles" ItemName="ls-temp-FilesCopied"/>
    </Copy>
    <Copy SourceFiles="@(_ls-ItemsToZip)"
          DestinationFiles="@(_ls-ItemsToZip->'$(_ls-IntermediateItemTemplateFolder)%(RecursiveDir)%(Filename)%(Extension)')"
          UseHardLinksIfPossible="$(ls-UseHardLinksForItemTemplatesCopy)">
      <Output TaskParameter ="CopiedFiles" ItemName="ls-temp-FilesCopied"/>
    </Copy>

    <Message Text="_ls-ItemTemplatesOutputs.Filename : [%(_ls-ItemTemplatesOutputs.Filename)]" Importance="high"/>
    <Message Text="Zipping the following files for Item Template: @(ls-temp-FilesCopied)" Importance="high"/>
    <Message Text="***: _ls-ItemTemplatesOutputs.OutputPathWithFileName:[%(_ls-ItemTemplatesOutputs.OutputPathWithFileName)]" Importance="high"/>
    <Message Text="***: _ls-IntermediateItemTemplateFolder:[$(_ls-IntermediateItemTemplateFolder)]" Importance="high" />
    <Message Text="***: _ls-ItemTemplatesOutputs.Identity:[%(_ls-ItemTemplatesOutputs.Identity)]" Importance="high" />
    <Message Text="***: _ls-ItemTemplatesOutputs.IntermediateItemTemplateFolder:[%(_ls-ItemTemplatesOutputs.IntermediateItemTemplateFolder)]" Importance="high" />
  </Target>

  <!-- This target will run once per value in @(ls-ItemTemplatesOutputs) -->
  <Target Name="ls-CreateZipForEachItemTemplate"
          Inputs="%(_ls-ItemTemplatesOutputs.VsTemplateSourcePath)" 
          Outputs="%(_ls-ItemTemplatesOutputs.Identity);All"
          DependsOnTargets="$(ls-CreateZipForEachItemTemplateDependsOn)">

    <PropertyGroup>
      <_ls-IntermediateItemTemplateFolder>$(ls-ItemTemplateOutputRoot)%(_ls-ItemTemplatesOutputs.ItemTemplateName)\</_ls-IntermediateItemTemplateFolder>
    </PropertyGroup>

    <ItemGroup>
      <_ls-IntFilesToZip Remove="@(_ls-IntFilesToZip)"/>
      <!-- Exclude the _Definitions folder from being zipped -->
      <_ls-IntFilesToZip Include="$(_ls-IntermediateItemTemplateFolder)**\*"
                         Exclude="$(_ls-IntermediateItemTemplateFolder)_Definitions\**\*" />
    </ItemGroup>    
    
    <!-- TODO: Does the .vstemplate file need to go into the .zip file? -->
    <MSBuild.ExtensionPack.Compression.Zip
      TaskAction="Create"
      CompressFiles="@(_ls-IntFilesToZip)"
      ZipFileName="%(_ls-ItemTemplatesOutputs.Identity)"
      RemoveRoot="$(_ls-IntermediateItemTemplateFolder)"
      CompressionLevel="BestCompression" />
    
    <ItemGroup>
      <ls-ItemTempZipIntermediateFiles Include="%(_ls-ItemTemplatesOutputs.Identity)"/>
    </ItemGroup>
    
  </Target>

  <Target Name="ls-InitalizeItemTemplateOutputFolder">
    <MakeDir Directories="$(ls-ItemTemplateOutputRoot)"/>
  </Target>

  <PropertyGroup>
    <ls-CalculateItemGroupOutputsForItemTemplates>
      $(ls-CalculateItemGroupOutputsForItemTemplates);
      ls-DiscoverItemTemplateFiles
    </ls-CalculateItemGroupOutputsForItemTemplates>
  </PropertyGroup>
  <!-- This target will run once per value in @(ls-ItemTemplateOutputRoot) -->
  <Target Name="ls-CalculateItemGroupOutputsForItemTemplates" 
          Inputs="%(ls-VsTemplateFiles.Identity)"
          Outputs="%(ls-VsTemplateFiles.Identity);All"
          DependsOnTargets="$(ls-CalculateItemGroupOutputsForItemTemplates)">

    <Message Text="ls-CalculateItemGroupOutputsForItemTemplates. ls-VsTemplateFiles:[ @(ls-VsTemplateFiles)]" />
    <!-- By the time this target is called the item ls-DiscoverItemTemplateFiles should be fully populated. 
    No additions after this point -->

    <PropertyGroup>
      <_TemplatesRoot>%(ls-VsTemplateFiles.TemplatesRoot)</_TemplatesRoot>
      <_ZipRootFolder>%(ls-VsTemplateFiles.ZipRootFolder)</_ZipRootFolder>
    </PropertyGroup>

    <Message Text="_TemplatesRoot:[$(_TemplatesRoot)]" Importance="high"/>
    <Message Text="_ZipRootFolder:[$(_ZipRootFolder)]" Importance="high"/>
    
    <!-- ls-ItemTemplateOutputRoot -->
    <GetItemTemplateNameFromVSTemplatePath 
      VstemplateFilePath="@(ls-VsTemplateFiles)"
      ItemTemplateRoot="$(_TemplatesRoot)"
      ItemTemplateZipRootFolder="$(_ZipRootFolder)"
      CustomTemplatesFolder="$(ls-TemplateSubFolder)">
      <Output TaskParameter="ItemTemplateName" PropertyName="_ls-ItemTemplateName" />
      <Output TaskParameter="ItemTemplateFolder" PropertyName="_ls-ItemTemplateFolder" />
      <Output TaskParameter="OutputPathWithFileName" PropertyName="OutputPathWithFileName" />
      <Output TaskParameter="OutputPathFolder" PropertyName="OutputPathFolder"/>
    </GetItemTemplateNameFromVSTemplatePath>
    
    <ItemGroup>
      <_ls-ItemTemplatesOutputs Include="@(ls-VsTemplateFiles->'$(ls-ItemTemplateOutputRoot)$(_ls-ItemTemplateName).zip')">
        <ItemTemplateName>$(_ls-ItemTemplateName)</ItemTemplateName>
        <VsTemplateSourcePath>%(ls-VsTemplateFiles.Identity)</VsTemplateSourcePath>
        <ItemTemplateFolder>$(_ls-ItemTemplateFolder)</ItemTemplateFolder>

        <OutputPathWithFileName>$(OutputPathWithFileName)</OutputPathWithFileName>
        <OutputPathFolder>$(OutputPathFolder)</OutputPathFolder>
      </_ls-ItemTemplatesOutputs>
    </ItemGroup>

    <Message Text="_ls-ItemTemplatesOutputs.ItemTemplateName: [%(_ls-ItemTemplatesOutputs.ItemTemplateName)]" Importance="high" />
    <Message Text="_ls-ItemTemplatesOutputs.Identity: [%(_ls-ItemTemplatesOutputs.Identity)]" Importance="high" />
    <Message Text="ls-ItemTemplateZipRootFolder: $(ls-ItemTemplateZipRootFolder)" Importance="high" />
    <Message Text="OutputPathWithFileName:$(OutputPathWithFileName)" Importance="high"/>
    <Message Text="%(_ls-ItemTemplatesOutputs.OutputPathWithFileName)" Importance="high"/>

    <Message Text="_ls-ItemTemplatesOutputs.VsTemplateSourcePath: %(_ls-ItemTemplatesOutputs.VsTemplateSourcePath)" />
  </Target>

  <PropertyGroup>
    <ls-AddCreatedItemTemplateZipFilesToProjectDependsOn>
      $(ls-AddCreatedItemTemplateZipFilesToProjectDependsOn);
      ls-CreateZipForEachItemTemplate;
    </ls-AddCreatedItemTemplateZipFilesToProjectDependsOn>
  </PropertyGroup>
  
  <Target Name="ls-AddCreatedItemTemplateZipFilesToProject" DependsOnTargets="$(ls-AddCreatedItemTemplateZipFilesToProjectDependsOn)" >
    <Message Text="Adding the following files to Content: [@(ls-ItemTempZipIntermediateFiles)]" />
    
    <!-- TODO: add this to VSIXSourceItem-->
    <!-- Add the produced .zip files to Content so that they are included in the package -->
    <ItemGroup>
      <VSIXSourceItem Include="%(_ls-ItemTemplatesOutputs.Identity)">
        <VSIXSubPath>%(_ls-ItemTemplatesOutputs.OutputPathFolder)</VSIXSubPath>
      </VSIXSourceItem>

    </ItemGroup>

    <Message Text="VSIXSubPath: [%(ls-ItemTempZipIntermediateFiles.OutputPathFolder)]" Importance="high"/>    
  </Target>

  <!--
    Preprocessing elements below
  -->
  <PropertyGroup>
    <ls-PreprocessTemplatesDependsOn>
      $(ls-PreprocessTemplatesDependsOn);
      ls-PreprocessDiscoverTempInfoFiles;
      ls-PreprocessEachTemplateInfoFile;
    </ls-PreprocessTemplatesDependsOn>
  </PropertyGroup>
  <Target Name="ls-PreprocessTemplates" DependsOnTargets="$(ls-PreprocessTemplatesDependsOn)"/>

  <!-- This target will find all the templateinfo.xml files -->
  <Target Name="ls-PreprocessDiscoverTempInfoFiles">
    <Message Text="Looking for templateinfo.xml files under [$(ls-ItemTemplateOutputRoot)]" Importance="low"/>
        <ItemGroup>
          <ls-TemplateInfoFiles Include="$(ls-ItemTemplateOutputRoot)**\_preprocess.xml" />
        </ItemGroup>

        <Message Text="ls-TemplateInfoFiles: @(ls-TemplateInfoFiles)"/>        
  </Target>

  <PropertyGroup>
    <ls-PreprocessEachTemplateInfoFileDependsOn>
      $(ls-PreprocessEachTemplateInfoFileDependsOn);
      ls-PreprocessDiscoverTempInfoFiles;
    </ls-PreprocessEachTemplateInfoFileDependsOn>
  </PropertyGroup>
  <!-- This will run once per file in @(ls-TemplateInfoFiles) -->
  <Target Name="ls-PreprocessEachTemplateInfoFile"
          Outputs="%(ls-TemplateInfoFiles.Identity)"
          DependsOnTargets="$(ls-PreprocessEachTemplateInfoFileDependsOn)">
          
    <Message Text="ls-TemplateInfoFiles.Identity: %(ls-TemplateInfoFiles.Identity)" Importance="low"/>
    <Message Text="ls-TemplateInfoFiles.Directory: %(ls-TemplateInfoFiles.Directory)" Importance="low"/>

    <PropertyGroup>
      <_TemplateInfoPath>%(ls-TemplateInfoFiles.FullPath)</_TemplateInfoPath>
      <_TemplateDir>%(ls-TemplateInfoFiles.RootDir)%(ls-TemplateInfoFiles.Directory)</_TemplateDir>
    </PropertyGroup>
    
    <Message Text="_TemplateInfoPath: [$(_TemplateInfoPath)]" Importance="low"/>
    <Message Text="_TemplateDir: [$(_TemplateDir)]" Importance="low"/>

    <ReplaceInFiles
      RootDirectory="$(_TemplateDir)"
      TemplateInfoFile="$(_TemplateInfoPath)"
      Condition="Exists('$(_TemplateInfoPath)')" />
    
    <Message Text="Skipping ReplaceInFiles because no _preprocess.xml files were found" 
             Condition="!Exists('$(_TemplateInfoPath)')"/>
  </Target>

  <PropertyGroup>
    <CleanDependsOn>
      $(CleanDependsOn);
      CleanTemplateBuilderFiles
    </CleanDependsOn>
    <CleanTemplateBuilderFilesDependsOn>
      $(CleanTemplateBuilderFilesDependsOn);      
    </CleanTemplateBuilderFilesDependsOn>
  </PropertyGroup>
  <Target Name="CleanTemplateBuilderFiles" 
          DependsOnTargets="$(CleanTemplateBuilderFilesDependsOn)"
          >
    <Message Text="Deleting template-builder files under [$(ls-ItemTemplateOutputRoot)]"/>
    <ItemGroup Condition=" '$(ls-ItemTemplateOutputRoot)'!='' ">
      <_TemplateBuilderFiles Remove="@(_TemplateBuilderFiles)"/>
      <_TemplateBuilderFiles Include="$(ls-ItemTemplateOutputRoot)**\*"/>
    </ItemGroup>
    <Delete Files="@(_TemplateBuilderFiles)" Condition=" '$(ls-ItemTemplateOutputRoot)'!='' "/>
    <RemoveDir Directories="$(ls-ItemTemplateOutputRoot)"/>
  </Target>
  <!--************************************************************************************
      Snippet support
  ************************************************************************************-->
  <Target Name="IncludeSnippetFilesInVsix">
    <Message Text="Ensuring .snippet files are marked as content and included in the .vsix"/>
    <!-- 
    We need to remove .snippet files from Content/None/Resource/EmbeddedResource
    Then add the files to Content with the following metadata set:
      <IncludeInVSIX>true</IncludeInVSIX>
    -->

    <FindUnderPath Files="@(Content);@(None);@(Resource);@(EmbeddedResource)" Path="$(ls-SnippetFolderRoot)">
      <Output TaskParameter="InPath" ItemName="_ls-Snippet-Files"/>
    </FindUnderPath>
    
    <ItemGroup>
      <Content Remove="@(_ls-Snippet-Files)"/>
      <None Remove="@(_ls-Snippet-Files)"/>
      <Resource Remove="@(_ls-Snippet-Files)"/>
      <EmbeddedResource Remove="@(_ls-Snippet-Files)"/>
    </ItemGroup>

    <Message Text="Adding the following .snippet files: [@(_ls-Snippet-Files)]" Importance="high"/>
    
    <ItemGroup>
      <Content Include="@(_ls-Snippet-Files)">
        <IncludeInVSIX>true</IncludeInVSIX>
      </Content>
    </ItemGroup>    
  </Target>

  <!--************************************************************************************
      Inline Tasks defined below
  ************************************************************************************-->
  <UsingTask TaskName="GetItemTemplateNameFromVSTemplatePath" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
    <ParameterGroup>
      <VstemplateFilePath ParameterType="System.String" Required="true"/>
      <ItemTemplateRoot ParameterType="System.String" Required="true"/>
      <!-- If provided this value should end in a '\' -->
      <ItemTemplateZipRootFolder ParameterType="System.String" Required="false"/>
      <CustomTemplatesFolder ParameterType="System.String" Required="false" />
      
      <!-- Outputs -->
      <ItemTemplateName ParameterType="System.String" Output="true"/>
      <ItemTemplateFolder ParameterType="System.String" Output="true"/>
      <ZipfileName ParameterType="System.String" Output="true"/>
      <OutputPathFolder ParameterType="System.String" Output="true"/>
      <OutputPathWithFileName ParameterType="System.String" Output="true" />
    </ParameterGroup>
    <Task>
      <Reference Include="System.Core" />
      <Using Namespace="System" />
      <Using Namespace="System.IO" />
      <Using Namespace="System.Net" />
      <Using Namespace="Microsoft.Build.Framework" />
      <Using Namespace="Microsoft.Build.Utilities" />
      <Code Type="Fragment" Language="cs">
        <![CDATA[
                Log.LogMessage("GetItemTemplateNameFromVSTemplatePath Starting");
                System.IO.FileInfo fi = new System.IO.FileInfo(VstemplateFilePath);
                System.IO.DirectoryInfo di = fi.Directory;

                var ItemTemplateFolderInfo = new System.IO.FileInfo(di.Parent.FullName);
                ItemTemplateFolder = ItemTemplateFolderInfo.FullName + @"\";

                // we need to get the name of the first folder under 'ItemTemplates' (ItemTemplateRoot)
                var itemTemplateRootUri = new Uri(ItemTemplateRoot);
                var relFolder = itemTemplateRootUri.MakeRelativeUri(new Uri(VstemplateFilePath)).ToString();
                var templateRelPath = relFolder.Substring(0, relFolder.IndexOf('/'));

                if (ItemTemplateZipRootFolder == null) {
                    ItemTemplateZipRootFolder = string.Empty;
                }

                string itRootFileName = di.Parent.Name;
                string subFolder = this.CustomTemplatesFolder;

                ZipfileName = string.Format(
                  "{0}{1}.zip",
                  ItemTemplateName,
                  fi.Name);
                // set OutputFolder
                // if the name is 
                //  'CSharp.vstemplate' -> CSharp\
                //  'Web.CSharp.vstemplate' -> CSharp\Web\
                //  'VB.vstemplate' -> VisualBasic\
                //  'Web.VB.vstemplate' -> VisualBasic\Web\
                if (string.Compare(@"CSharp.vstemplate", fi.Name, StringComparison.OrdinalIgnoreCase) == 0) {
                    ItemTemplateName = string.Format("{0}.csharp", itRootFileName);
                    OutputPathFolder = string.Format(@"{0}CSharp\{1}\{2}", ItemTemplateZipRootFolder, templateRelPath, subFolder);
                }
                else if (string.Compare(@"Web.CSharp.vstemplate", fi.Name, StringComparison.OrdinalIgnoreCase) == 0) {
                    ItemTemplateName = string.Format("{0}.web.csharp", itRootFileName);

                    // web site templates do not support any nesting
                    OutputPathFolder = string.Format(@"{0}CSharp\Web\{1}", ItemTemplateZipRootFolder, subFolder);
                }
                else if (string.Compare(@"VB.vstemplate", fi.Name, StringComparison.OrdinalIgnoreCase) == 0) {
                    ItemTemplateName = string.Format("{0}.VB", itRootFileName);
                    OutputPathFolder = string.Format(@"{0}VisualBasic\{1}\{2}", ItemTemplateZipRootFolder, templateRelPath, subFolder);
                }
                else if (string.Compare(@"Web.VB.vstemplate", fi.Name, StringComparison.OrdinalIgnoreCase) == 0) {
                    ItemTemplateName = string.Format("{0}.web.VB", itRootFileName);

                    // web site templates do not support any nesting
                    OutputPathFolder = string.Format(@"{0}VisualBasic\Web\{1}", ItemTemplateZipRootFolder, subFolder);
                }
                else {
                    Log.LogError("Unknown value for ItemTemplateName: [{0}]. Supported values include 'CSharp.vstemplate','Web.CSharp.vstemplate','VB.vstemplate' and 'Web.VB.vstemplate' ", fi.Name);
                    return false;
                }

                OutputPathWithFileName = string.Format(@"{0}{1}", OutputPathFolder, itRootFileName);   
            ]]>
      </Code>
    </Task>
  </UsingTask>
  
  <UsingTask TaskName="ReplaceInFiles" AssemblyFile="$(ls-TasksRoot)LigerShark.TemplateBuilder.Tasks.dll"/>

  <UsingTask TaskName="ParseTemplateInfoFile" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
    <ParameterGroup>
      <FilePath ParameterType="System.String" Required="true"/>
      <ReplacementsItemSpec ParameterType="System.String" />

      <!-- Outputs -->
      <Include ParameterType="System.String" Output="true"/>
      <Exclude ParameterType="System.String" Output="true"/>
      <Replacements ParameterType="Microsoft.Build.Framework.ITaskItem[]" Output="true"/>
    </ParameterGroup>
    <Task>
      <Reference Include="System.Core" />
      <Reference Include="System.Xml" />
      <Reference Include="System.Xml.Linq" />
      <Using Namespace="System" />
      <Using Namespace="System.IO" />
      <Using Namespace="System.Net" />
      <Using Namespace="System.Xml.Linq"/>
      <Using Namespace="Microsoft.Build.Framework" />
      <Using Namespace="Microsoft.Build.Utilities" />
      <Code Type="Fragment" Language="cs">
        <![CDATA[
         Log.LogMessage("ParseTemplateInfoFile called on file [{0}]", FilePath);

            if (!File.Exists(FilePath)) {
                Log.LogError("templateinfo.xml file not found at [{0}]",FilePath);
                return false;
            }
            if(string.IsNullOrEmpty(ReplacementsItemSpec)){
                ReplacementsItemSpec = "Replacements";
            }

            try {
                XDocument doc = XDocument.Load(FilePath);
                var result = (from r in doc.Root.Elements("Replacements")
                             select new {
                                 Include = r.Attribute("Include").Value,
                                 Exclude = r.Attribute("Exclude").Value,
                                 Replacements = (
                                     from a in r.Elements("add")
                                     select new {
                                         Key = a.Attribute("key").Value,
                                         Value = a.Attribute("value").Value
                                     }
                                 )
                             }).Single();

                this.Include = result.Include;
                this.Exclude = result.Exclude;
                List<ITaskItem> repList = new List<ITaskItem>();
                
                foreach(var item in result.Replacements){
                    ITaskItem rep = new TaskItem(ReplacementsItemSpec);
                    rep.SetMetadata(item.Key, item.Value);
                    repList.Add(rep);
                }

                Replacements = repList.ToArray();

            }
            catch (Exception ex) {
                Log.LogError("Unable to parse template info file [{0}]. Details=[{1}]",FilePath,ex.ToString());
                return false;
            }
            return true;    
        ]]>
      </Code>
    </Task>
  </UsingTask>
</Project>