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

  <PropertyGroup>
    <NativeExecutableExtension Condition=" $(Rid.StartsWith('win'))">.exe</NativeExecutableExtension>
    <AppHostExecutableName>AppHost$(NativeExecutableExtension)</AppHostExecutableName>
  </PropertyGroup>

  <Target Name="ExtractAppHostToOutput"
          Condition="!Exists('$(AppHostTemplatePath)/$(AppHostExecutableName)')"
          DependsOnTargets="EnsureAppHostPackageRestored">

    <Message Text="Restore $(TemplateFillInPackageName) from $(AppHostTemplatePath) to $(AppHostTemplateRestoreAdditionalParameters)."
             Importance="High" />

    <ItemGroup>
      <AllFileOfRestoredAppHostPackage Include="$(AppHostIntermediateDirectory)\**\*.*" />
      <NativeRestoredAppHostNETCore
          Include="@(AllFileOfRestoredAppHostPackage)"
          Condition="'%(FileName)%(Extension)' == '$(AppHostExecutableName)'"/>
    </ItemGroup>

    <Error Condition="@(NativeRestoredAppHostNETCore->Distinct()->Count()) != 1"
           Text="Failed to determine the $(_NETCoreDotNetAppHostPackageName) executable in $(AllFileOfRestoredAppHostPackage)" />

    <Copy
        SourceFiles="@(NativeRestoredAppHostNETCore)"
        DestinationFolder="$(AppHostTemplatePath)" />

    <Message Text="Copy from @(NativeRestoredAppHostNETCore) to $(AppHostTemplatePath)."
             Importance="High" />

  </Target>

  <Target Name="EnsureAppHostPackageRestored">
    <PropertyGroup>
      <AppHostTemplateRestoreAdditionalParameters>--runtime $(Rid)</AppHostTemplateRestoreAdditionalParameters>
      <AppHostTemplateRestoreAdditionalParameters>$(AppHostTemplateRestoreAdditionalParameters) /p:TargetFramework=$(CliTargetFramework)</AppHostTemplateRestoreAdditionalParameters>
      <AppHostTemplateRestoreAdditionalParameters>$(AppHostTemplateRestoreAdditionalParameters) /p:TemplateFillInPackageName=$(TemplateFillInPackageName)</AppHostTemplateRestoreAdditionalParameters>
      <AppHostTemplateRestoreAdditionalParameters>$(AppHostTemplateRestoreAdditionalParameters) /p:TemplateFillInPackageVersion=$(TemplateFillInPackageVersion)</AppHostTemplateRestoreAdditionalParameters>
      <AppHostTemplateRestoreAdditionalParameters>$(AppHostTemplateRestoreAdditionalParameters) /p:RestorePackagesPath=$(AppHostIntermediateDirectory)</AppHostTemplateRestoreAdditionalParameters>
    </PropertyGroup>

    <DotNetRestore ToolPath="$(PreviousStageDirectory)"
                   ProjectPath="$(MSBuildThisFileDirectory)/templates/templates.csproj"
                   AdditionalParameters="$(AppHostTemplateRestoreAdditionalParameters)" />
  </Target>
</Project>
