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

  <UsingTask TaskName="DotNetDebTool" AssemblyFile="$(CLIBuildDll)" />

  <Import Project="Installer.DEB.targets" />

  <!-- Re-enable "TestSdkDeb" when the following issue is resolved: https://github.com/dotnet/cli/issues/9672 -->
  <Target Name="GenerateDebs"
          DependsOnTargets="SetupDebProps;
                            TestDebuild;
                            BuildSdkDeb"
          Condition=" '$(IsDebianBaseDistro)' == 'True' "
          Outputs="@(GeneratedInstallers)"/>

  <Target Name="GetAspNetSharedFxInstallArgs" DependsOnTargets="EvaluateRuntimeCoherence">
    <PropertyGroup>
      <!-- Ignored because versions of aspnetcore-runtime may be in incoherent with the version of dotnet-runtime we want to use. -->
      <InstallAspNetCoreSharedFxArgs>--ignore-depends=dotnet-runtime-$(AspNetCoreSharedFxBaseRuntimeVersion)</InstallAspNetCoreSharedFxArgs>
    </PropertyGroup>
  </Target>

  <Target Name="BuildSdkDeb"
      Condition=" '$(IsDebianBaseDistro)' == 'True' AND '$(DebuildPresent)'  == 'true' "
      DependsOnTargets="PrepareDotnetDebDirectories;
                        PrepareDotnetDebTool;
                        GetAspNetSharedFxInstallArgs;"
      Inputs="@(CLISdkFiles)"
      Outputs="$(SdkInstallerFile)" >
      <!-- Install Shared Framework Packages -->

      <Exec Command="sudo dpkg -i $(DownloadedRuntimeDepsInstallerFile)" />
      <Exec Command="sudo dpkg -i $(DownloadedSharedHostInstallerFile)" />
      <Exec Command="sudo dpkg -i $(DownloadedHostFxrInstallerFile)" />
      <Exec Command="sudo dpkg -i $(DownloadedSharedFrameworkInstallerFile)" />
      <Exec Command="sudo dpkg $(InstallAspNetCoreSharedFxArgs) -i $(DownloadedAspNetCoreSharedFxInstallerFile)" />

      <!-- Create layout: Binaries -->
      <Copy
        DestinationFiles="@(CLISdkFiles->'$(LayoutPackageRootDir)/sdk/%(RecursiveDir)%(Filename)%(Extension)')"
        SourceFiles="@(CLISdkFiles)"
        OverwriteReadOnlyFiles="True"
        SkipUnchangedFiles="False"
        UseHardlinksIfPossible="False" />

      <!-- Create layout: Man Pages -->
      <Copy
        DestinationFiles="@(SdkDebManPageFiles->'$(LayoutDocsDir)/%(RecursiveDir)%(Filename)-$(SdkVersion)%(Extension)')"
        SourceFiles="@(SdkDebManPageFiles)"
        OverwriteReadOnlyFiles="True"
        SkipUnchangedFiles="False"
        UseHardlinksIfPossible="False" />

      <!-- Create layout: Generate and Place postinst -->
      <ReplaceFileContents
        InputFiles="$(DebianPostinstTemplateFile)"
        DestinationFiles="$(DebianPostinstFile)"
        ReplacementItems="@(DebianPostInstTokenValues)" />

      <Chmod
        Glob="$(DebianPostinstFile)"
        Mode="ugo+x" />

      <!-- Create layout: Generate and Place debian_config.json -->
      <ReplaceFileContents
        InputFiles="$(DebianConfigTemplateFile)"
        DestinationFiles="$(DebianConfigJsonFile)"
        ReplacementItems="@(DebianConfigTokenValues)" />

      <Chmod
        Glob="$(PackageTool)"
        Mode="u+x" />

      <!-- Build SDK Deb package -->
      <DotNetDebTool ToolPath="$(PreviousStageDirectory)"
                     InputDirectory="$(LayoutDirectory)"
                     OutputDirectory="$(DotNetDebToolOutputDirectory)"
                     PackageName="$(SdkDebianPackageName)"
                     PackageVersion="$(SdkVersion)"
                     WorkingDirectory="$(DotnetDebToolDir)" />

      <!-- Copy SDK package to output -->
      <ItemGroup>
        <GeneratedDebFiles Include="$(DotNetDebToolOutputDirectory)/*.deb" />
      </ItemGroup>

      <Error Text="@(GeneratedDebFiles->Count()) .deb files generated." Condition="'@(GeneratedDebFiles->Count())' != 1" />

      <Copy
        DestinationFiles="$(SdkInstallerFile)"
        SourceFiles="@(GeneratedDebFiles)"
        OverwriteReadOnlyFiles="True"
        SkipUnchangedFiles="False"
        UseHardlinksIfPossible="False" />

      <!-- Proactively remove all possible Shared Framework and Debian Packages -->
      <ItemGroup>
        <SetupDebPackageToRemove Include="$(SdkDebianPackageName)" />
        <SetupDebPackageToRemove Include="$(AspNetCoreSharedFxDebianPackageName)" />
        <SetupDebPackageToRemove Include="$(AspNetCoreSharedFxDebianPackageFileName)" />
        <SetupDebPackageToRemove Include="$(SharedFxDebianPackageName)" />
        <SetupDebPackageToRemove Include="$(SharedFxDebianPackageFileName)" />
        <SetupDebPackageToRemove Include="$(HostFxrDebianPackageName)" />
        <SetupDebPackageToRemove Include="$(HostFxrDebianPackageFileName)" />
        <SetupDebPackageToRemove Include="$(HostDebianPackageName)" />
        <SetupDebPackageToRemove Include="$(RuntimeDepsPackageName)" />
      </ItemGroup>
      <!-- The following line is needed. So it won't warning dotnet folder is not empty after uninstall -->
      <Exec Command="sudo rm -rf /usr/share/dotnet/sdk/NuGetFallbackFolder" />
      <Exec Command="!(dpkg-query -W %(SetupDebPackageToRemove.Identity)) || sudo dpkg -r %(SetupDebPackageToRemove.Identity)" />
  </Target>

  <Target Name="TestSdkDeb"
      Condition=" '$(CLIBUILD_SKIP_TESTS)' != 'true' and '$(IsDebianBaseDistro)' == 'True' and '$(DebuildPresent)'  == 'true' "
      DependsOnTargets="RestoreTests;GetAspNetSharedFxInstallArgs"
      Inputs="$(DownloadedSharedHostInstallerFile);
              $(DownloadedHostFxrInstallerFile);
              $(DownloadedSharedFrameworkInstallerFile);
              $(SdkInstallerFile);"
      Outputs="$(DebianTestResultsXmlFile)" >

      <!-- Install Dependencies and SDK Packages -->
      <Exec Command="sudo dpkg -i $(DownloadedRuntimeDepsInstallerFile)" />
      <Exec Command="sudo dpkg -i $(DownloadedSharedHostInstallerFile)" />
      <Exec Command="sudo dpkg -i $(DownloadedHostFxrInstallerFile)" />
      <Exec Command="sudo dpkg -i $(DownloadedSharedFrameworkInstallerFile)" />
      <Exec Command="sudo dpkg $(InstallAspNetCoreSharedFxArgs) -i $(DownloadedAspNetCoreSharedFxInstallerFile)" />

      <Exec Command="sudo dpkg -i $(SdkInstallerFile)" />

      <!-- Run E2E -->
      <DotNetRestore ProjectPath="$(EndToEndTestProject)"
                     ToolPath="$(DebianInstalledDirectory)" />

      <DotNetTest ProjectPath="$(EndToEndTestProject)"
                  EnvironmentVariables="@(TestSdkDebTaskEnvironmentVariables)"
                  ToolPath="$(DebianInstalledDirectory)" />

      <!-- Clean up Packages -->
      <!-- The following line is needed. So it won't warning dotnet folder is not empty after uninstall -->
      <Exec Command="sudo rm -rf /usr/share/dotnet/sdk/NuGetFallbackFolder" />

      <ItemGroup>
        <TestSdkDebPackageToRemove Include="$(SdkDebianPackageName)" />
        <TestSdkDebPackageToRemove Include="$(AspNetCoreSharedFxDebianPackageName)" />
        <TestSdkDebPackageToRemove Include="$(SharedFxDebianPackageName)" />
        <TestSdkDebPackageToRemove Include="$(HostFxrDebianPackageName)" />
        <TestSdkDebPackageToRemove Include="$(HostDebianPackageName)" />
        <TestSdkDebPackageToRemove Include="$(RuntimeDepsPackageName)"/>
      </ItemGroup>
      <!-- If package installed remove it -->
      <Exec Command="!(dpkg-query -W %(TestSdkDebPackageToRemove.Identity)) || sudo dpkg -r %(TestSdkDebPackageToRemove.Identity)" />
  </Target>

  <Target Name="PrepareDotnetDebDirectories">

    <!-- Clean the workspace -->
    <ItemGroup>
      <FilesToClean Remove="*" />
      <FilesToClean Include="$(SdkInstallerFile)" />

      <WorkspaceDirectories Remove="*" />
      <WorkspaceDirectories Include="$(SdkDebianIntermediateDirectory);
                                     $(LayoutDirectory)" />

      <LayoutSubDirectories Remove="*" />
      <LayoutSubDirectories Include="$(LayoutPackageRootDir);
                                     $(LayoutAbsolutePlacementDir);
                                     $(LayoutSamplesDir);
                                     $(LayoutDocsDir);
                                     $(LayoutDebianFilesDir)" />
    </ItemGroup>

    <Delete Files="@(FilesToClean)" />
    <RemoveDir Directories="@(WorkspaceDirectories)" />

    <!-- Rebuild the workspace -->
    <MakeDir Directories="@(WorkspaceDirectories)" />
    <MakeDir Directories="@(LayoutSubDirectories)" />
    <MakeDir Directories="$(DotNetDebToolOutputDirectory)" />
  </Target>

  <Target Name="PrepareDotnetDebTool">

    <DotNetRestore ToolPath="$(PreviousStageDirectory)"
                   WorkingDirectory="$(DotnetDebToolDir)" />
  </Target>

  <Target Name="TestDebuild">
      <Message Text="Don't remove this" />

      <!-- run Debuild  -->
      <!-- NB: IgnoreExitCode prevents Exec from failing, but does not prevent us from retrieving the exit code. -->
      <Exec Command="/usr/bin/env debuild -h > /dev/null 2>&amp;1" IgnoreExitCode="true">
          <Output TaskParameter="ExitCode" PropertyName="DebuildExitCode" />
      </Exec>

      <!-- Check if it returned 0 -->
      <PropertyGroup>
        <DebuildPresent>false</DebuildPresent>
        <DebuildPresent Condition=" '$(DebuildExitCode)' == '0' ">true</DebuildPresent>
      </PropertyGroup>

      <!-- Workaround for Ubuntu16 Jenkins https://github.com/dotnet/core-setup/issues/167 -->
      <Message Condition=" '$(DebuildPresent)'  != 'true' "
               Text="Debuild Not found, Debian packages will not be built."
               Importance="High" />
  </Target>
</Project>
