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

    <ItemGroup>
        <WebStackNuGetPackages Include="DotNetOpenAuth.AspNet"/>
        <WebStackNuGetPackages Include="DotNetOpenAuth.Core"/>
        <WebStackNuGetPackages Include="DotNetOpenAuth.OAuth.Consumer"/>
        <WebStackNuGetPackages Include="DotNetOpenAuth.OAuth.Core"/>
        <WebStackNuGetPackages Include="DotNetOpenAuth.OpenId.Core"/>
        <WebStackNuGetPackages Include="DotNetOpenAuth.OpenId.RelyingParty"/>
        <WebStackNuGetPackages Include="EntityFramework"/>
        <WebStackNuGetPackages Include="Microsoft.Web.FxCop"/>
        <WebStackNuGetPackages Include="Microsoft.Web.Infrastructure"/>
        <WebStackNuGetPackages Include="Moq"/>
        <WebStackNuGetPackages Include="Newtonsoft.Json"/>
        <WebStackNuGetPackages Include="Nuget.Core"/>
        <WebStackNuGetPackages Include="StyleCop"/>
        <WebStackNuGetPackages Include="xunit"/>
        <WebStackNuGetPackages Include="xunit.extensions"/>
    </ItemGroup>

    <PropertyGroup>
        <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">$(MSBuildProjectDirectory)\..\</SolutionDir>
        <NuGetToolsPath>$([System.IO.Path]::Combine($(SolutionDir), "Tools"))</NuGetToolsPath>
        <NuGetExePath>$(NuGetToolsPath)\NuGet.exe</NuGetExePath>
        <PackagesConfig>$([System.IO.Path]::Combine($(ProjectDir), "packages.config"))</PackagesConfig>
        <PackagesDir>$([System.IO.Path]::Combine($(SolutionDir), "packages"))</PackagesDir>
        <PackageOutputDir Condition="'$(PackageOutputDir)' == ''">$(TargetDir.Trim('\\'))</PackageOutputDir>
        <PreReleasePackagesUrl Condition="'$(PreReleasePackagesUrl)' == ''">http://www.myget.org/F/f05dce941ae4485090b04586209c8b08/</PreReleasePackagesUrl>
        <CompactMessage Condition=" '$(CompactMessage)' == '' ">true</CompactMessage>

        <!-- Package sources used to restore packages. By default will used the registered sources under %APPDATA%\NuGet\NuGet.Config -->
        <PackageSources>"https://go.microsoft.com/fwlink/?LinkID=230477;$(PreReleasePackagesUrl)"</PackageSources>

        <!-- Enable the restore command to run before builds -->
        <RestorePackages Condition="$(RestorePackages) == ''">false</RestorePackages>

        <!-- Property that enables building a package from a project -->
        <BuildPackage Condition="$(BuildPackage) == ''">false</BuildPackage>

        <!-- Commands -->
        <RestoreCommand>"$(NuGetExePath)" install "$(PackagesConfig)" -source $(PackageSources) -o "$(PackagesDir)" > NUL</RestoreCommand>
        <BuildCommand>"$(NuGetExePath)" pack "$(ProjectPath)" -p Configuration=$(Configuration) -o "$(PackageOutputDir)" -symbols</BuildCommand>

        <!-- Make the build depend on restore packages -->
        <BuildDependsOn Condition="$(RestorePackages) != 'true'">
            VerifyPackages;
            $(BuildDependsOn);
        </BuildDependsOn>

        <BuildDependsOn Condition="$(RestorePackages) == 'true'">
            RestorePackages;
            $(BuildDependsOn);
        </BuildDependsOn>

        <!-- Make the build depend on restore packages -->
        <BuildDependsOn Condition="$(BuildPackage) == 'true'">
            $(BuildDependsOn);
            BuildPackage;
        </BuildDependsOn>
    </PropertyGroup>

    <Target Name="VerifyPackages">
        <CheckForPackages Packages="@(WebStackNuGetPackages)" PackagesDir="$(PackagesDir)" CompactMessage="$(CompactMessage)" />
    </Target>

    <Target Name="CheckPrerequisites">
        <DownloadNuGet OutputFilename="$(NuGetExePath)" Condition="!Exists('$(NuGetExePath)')" />
    </Target>

    <Target Name="RestorePackages" DependsOnTargets="CheckPrerequisites">
        <Exec Command="$(RestoreCommand)"
              LogStandardErrorAsError="true"
              Condition="Exists('$(PackagesConfig)')" />
    </Target>

    <Target Name="RestoreBinaryDependencies">
        <Exec
            Command='"$(NuGetExePath)" install StyleCop -source $(PackageSources) -o "$(PackagesDir)" -Version 4.7.10.0 > NUL'
            LogStandardErrorAsError="true" />
        <Exec
            Command='"$(NuGetExePath)" install Microsoft.Web.FxCop -source $(PackageSources) -o "$(PackagesDir)" -ExcludeVersion > NUL'
            LogStandardErrorAsError="true"
            Condition=" !Exists('$(PackagesDir)\Microsoft.Web.FxCop') " />
    </Target>

    <Target Name="BuildPackage" DependsOnTargets="CheckPrerequisites">
        <Exec Command="$(BuildCommand)"
              LogStandardErrorAsError="true" />
    </Target>

    <UsingTask TaskName="DownloadNuGet" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
        <ParameterGroup>
            <OutputFilename ParameterType="System.String" Required="true" />
        </ParameterGroup>
        <Task>
            <Reference Include="System.Core" />
            <Reference Include="System.Xml" />
            <Reference Include="WindowsBase" />
            <Using Namespace="System" />
            <Using Namespace="System.IO" />
            <Using Namespace="System.IO.Packaging" />
            <Using Namespace="System.Linq" />
            <Using Namespace="System.Net" />
            <Using Namespace="System.Xml" />
            <Using Namespace="Microsoft.Build.Framework" />
            <Using Namespace="Microsoft.Build.Utilities" />
            <Code Type="Fragment" Language="cs">
                <![CDATA[
                string zipTempPath = null;

                try {
                    OutputFilename = Path.GetFullPath(OutputFilename);

                    if (File.Exists(OutputFilename)) {
                        return true;
                    }

                    Log.LogMessage("Determining latest version of NuGet.CommandLine...");
                    WebClient webClient = new WebClient();
                    XmlDocument xml = new XmlDocument();
                    xml.LoadXml(webClient.DownloadString("http://nuget.org/v1/FeedService.svc/Packages()?$filter=tolower(Id)%20eq%20'nuget.commandline'&$top=1&$orderby=Version%20desc"));
                    XmlNamespaceManager xns = new XmlNamespaceManager(xml.NameTable);
                    xns.AddNamespace("atom", "http://www.w3.org/2005/Atom");
                    xns.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices");
                    xns.AddNamespace("m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
                    string version = xml.SelectSingleNode("//atom:entry/m:properties/d:Version", xns).InnerText;
                    string zipUrl = xml.SelectSingleNode("//atom:entry/atom:content", xns).Attributes["src"].Value;

                    Log.LogMessage("Downloading NuGet.CommandLine v{0}...", version);
                    zipTempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
                    webClient.DownloadFile(zipUrl, zipTempPath);

                    Log.LogMessage("Copying to {0}...", OutputFilename);
                    using (Package package = Package.Open(zipTempPath)) {
                        PackagePart exePart = package.GetParts().Where(p => p.Uri.ToString().ToLowerInvariant() == "/tools/nuget.exe").Single();
                        using (Stream inputStream = exePart.GetStream(FileMode.Open, FileAccess.Read))
                        using (Stream outputStream = File.Create(OutputFilename)) {
                            byte[] buffer = new byte[16384];
                            while (true) {
                                int read = inputStream.Read(buffer, 0, buffer.Length);
                                if (read == 0) {
                                    break;
                                }
                                outputStream.Write(buffer, 0, read);
                            }
                        }
                    }

                    return true;
                }
                catch (Exception ex) {
                    Log.LogErrorFromException(ex);
                    return false;
                }
                finally {
                    if (zipTempPath != null) File.Delete(zipTempPath);
                }
            ]]>
            </Code>
        </Task>
    </UsingTask>
</Project>