<Project ToolsVersion="15.0" DefaultTargets="CopyTemplateToOutput">
  <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
  <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.tasks))\dir.tasks" />

  <Target Name="CopyTemplateToOutput"
          DependsOnTargets="PrepareBundledTemplateProps;
                            EnsureTemplateRestored;
                            GetTemplateItemsToCopy"
          Inputs="@(TemplateContent)"
          Outputs="@(TemplateContent->'$(TemplateLayoutDirectory)/%(RecursiveDir)%(FileName)%(Extension)')">
    <Copy SourceFiles="@(TemplateContent)"
          DestinationFiles="@(TemplateContent->'$(TemplateLayoutDirectory)/%(RecursiveDir)%(FileName)%(Extension)')" />
    
    <Message Text="Copied template $(TemplateFillInPackageName) from $(TemplateNuPkgPath) to $(TemplateLayoutDirectory)."
             Importance="High" />
  </Target>

  <Target Name="GetTemplateItemsToCopy">
    <ItemGroup>
      <TemplateContent Include="$(TemplateNuPkgPath)/$(TemplateFillInPackageName.ToLower()).$(TemplateFillInPackageVersion.ToLower()).nupkg" />
    </ItemGroup>
  </Target>

  <Target Name="EnsureTemplateRestored"
          Condition="!Exists('$(TemplateNuPkgPath)/$(TemplateFillInPackageName.ToLower()).nuspec')">
    <DotNetRestore ToolPath="$(PreviousStageDirectory)"
                   ProjectPath="$(MSBuildThisFileDirectory)/templates/templates.csproj"
                   AdditionalParameters="/p:TargetFramework=netcoreapp1.0 /p:TemplateFillInPackageName=$(TemplateFillInPackageName) /p:TemplateFillInPackageVersion=$(TemplateFillInPackageVersion)" />
  </Target>

  <Target Name="PrepareBundledTemplateProps">
    <PropertyGroup>
      <TemplateNuPkgPath>$(NuGetPackagesDir)/$(TemplateFillInPackageName.ToLower())/$(TemplateFillInPackageVersion.ToLower())</TemplateNuPkgPath>
    </PropertyGroup>
  </Target>
</Project>
