<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

  <PropertyGroup Condition="'$(GeneratePlatformNotSupportedAssembly)' == 'true'">
    <!-- Tell ResolveMatchingContract to run and resolve contract to project reference -->
    <ResolveMatchingContract>true</ResolveMatchingContract>
    <NotSupportedSourceFile>$(IntermediateOutputPath)$(TargetName).notsupported.cs</NotSupportedSourceFile>
    <CoreCompileDependsOn>$(CoreCompileDependsOn);GenerateNotSupportedSource</CoreCompileDependsOn>
    <OmitResources>true</OmitResources>
  </PropertyGroup>

  <ItemGroup Condition="'$(GeneratePlatformNotSupportedAssembly)' == 'true'">
    <AssemblyMetadata Include="NotSupported">
      <Value>True</Value>
    </AssemblyMetadata>
  </ItemGroup>

  <!-- GenerateNotSupportedSource
       Inputs:
         * A contract assembly
         * Reference assemblies

       Generates source for the contract that throws PlatformNotSupportedException
  -->
  <Target Name="GenerateNotSupportedSource" 
          DependsOnTargets="ResolveMatchingContract"
          Inputs="@(ReferencePath);@(ResolvedMatchingContract)"
          Outputs="$(NotSupportedSourceFile)">

    <ItemGroup>
      <!-- build out a list of directories where dependencies are located -->
      <_referencePathDirectoriesWithDuplicates Include="@(ReferencePath->'%(RootDir)%(Directory)'->TrimEnd('\'))" />
      <!-- strip metadata, removing duplicates -->
      <_referencePathDirectories Include="%(_referencePathDirectoriesWithDuplicates.Identity)" />
    </ItemGroup>

    <Error Text="No single matching contract found." Condition="'@(ResolvedMatchingContract->Count())' != '1'" />

    <PropertyGroup>
      <GenAPIArgs>-assembly:"%(ResolvedMatchingContract.Identity)"</GenAPIArgs>
      <GenAPIArgs>$(GenAPIArgs) -libPath:"@(_referencePathDirectories)"</GenAPIArgs>
      <GenAPIArgs>$(GenAPIArgs) -out:"$(NotSupportedSourceFile)"</GenAPIArgs>
      <GenAPIArgs>$(GenAPIArgs) -throw</GenAPIArgs>
    </PropertyGroup>

    <PropertyGroup>
      <GenAPICmd>$(ToolHostCmd) "$(ToolsDir)GenAPI.exe"</GenAPICmd>
    </PropertyGroup>

    <Exec Command="$(GenAPICmd) $(GenAPIArgs)" WorkingDirectory="$(ToolRuntimePath)" />

    <ItemGroup>
      <FileWrites Include="$(NotSupportedSourceFile)" />
      <Compile Include="$(NotSupportedSourceFile)" />
    </ItemGroup>
  </Target>

</Project>
