<Project ToolsVersion="15.0" DefaultTargets="EnsureDependencyRestored;CopySdkToOutput">
  <!-- workaround for https://github.com/Microsoft/msbuild/issues/885 -->
  <!-- renaming the property because the original property is a global property and therefore
       cannot be redefined at runtime. -->
  <PropertyGroup>
    <CLIBuildDllPath>$([MSBuild]::Unescape($(CLIBuildDll)))</CLIBuildDllPath>
  </PropertyGroup>

  <UsingTask TaskName="DotNetRestore" AssemblyFile="$(CLIBuildDllPath)" />

  <Target Name="CopySdkToOutput"
          DependsOnTargets="PrepareBundledDependencyProps;
                            EnsureDependencyRestored;
                            GetSdkItemsToCopy"
          Condition="'$(SdkLayoutDirectory)' != ''"
          Inputs="@(SdkContent)"
          Outputs="@(SdkContent->'$(SdkLayoutDirectory)/%(RecursiveDir)%(FileName)%(Extension)')">
    <Copy SourceFiles="@(SdkContent)"
          DestinationFiles="@(SdkContent->'$(SdkLayoutDirectory)/%(RecursiveDir)%(FileName)%(Extension)')" />
    
    <Message Text="Copied Sdk $(DependencyPackageName) from $(DependencyNuPkgPath) to $(SdkLayoutDirectory)."
             Importance="High" />
  </Target>

  <Target Name="GetSdkItemsToCopy">
    <ItemGroup>
      <SdkContent Include="$(DependencyNuPkgPath)/**/*" 
                  Exclude="$(DependencyNuPkgPath)/$(DependencyPackageName).nuspec;
                           $(DependencyNuPkgPath)/$(DependencyPackageName).$(DependencyPackageVersion).nupkg;
                           $(DependencyNuPkgPath)/$(DependencyPackageName).$(DependencyPackageVersion).nupkg.sha512" />
    </ItemGroup>
  </Target>

  <Target Name="EnsureDependencyRestored"
          Condition="!Exists('$(DependencyNuPkgPath)/$(DependencyPackageName.ToLower()).nuspec')">
    <DotNetRestore ToolPath="$(PreviousStageDirectory)"
                   ProjectPath="$(MSBuildThisFileDirectory)/sdks/sdks.csproj"
                   AdditionalParameters="/p:DependencyPackageName=$(DependencyPackageName) /p:DependencyPackageVersion=$(DependencyPackageVersion)" />
  </Target>

  <Target Name="PrepareBundledDependencyProps">
    <PropertyGroup>
      <DependencyNuPkgPath>$(NuGetPackagesDir)/$(DependencyPackageName.ToLower())/$(DependencyPackageVersion.ToLower())</DependencyNuPkgPath>
    </PropertyGroup>
  </Target>
</Project>
