#!/bin/bash

# Usage:
#   repack-dotnet-tarball link_to_ms_tarball
#
# Download the tarball from MS and erase some files
# not needed for the Ubuntu building.
# Recompression in xz format.




#trap on_exit TERM
#trap on_exit EXIT

set -euo pipefail
IFS=$'\n\t'

function print_usage {
    echo "Usage:"
    echo "$0 link"
    echo ""
    echo "Repack a source archive tarball for dotnet7"
    echo ""
    echo " link: http address from where we can download the tarball from MS"
    echo ""
#    echo " version (X.X.XXX): dotnet version to be cloned"
#    echo ""
    echo "example: $0 https://dotnetclimsrc.blob.core.[...]/[...]"
}

function on_exit {

    rm -rf dotnet
    rm -rf "${dir_name}"
}


function clean_uscan_download {
   find .. -name "dotnet*${version}*.tar.*" -delete
}


set -x

if [[ "$#" -gt 0 ]]; then
    if [ "${1}" = "-h" ] || [ "${1}" = "--help" ]; then
       print_usage
       exit 0
    else
	    link="${1}"
	    ms_tarball=$(echo "${link}" | sed -r 's|.*/([^/]+tar.gz)\?.*|\1|')
	    version=$(echo "${ms_tarball}" | sed -r 's|.*-(.*).tar.gz|\1|')
        dotnet=${version%%.*}
    fi
else
    echo "Not enought arguments to run properly:"
    print_usage
    exit 1
fi

#we are not using uscan at the moment, because azure repo is not compatible
#with the protocols we can use in the watch file
#clean_uscan_download

#Change this for incorporating dotnet or new architecture to a Ubuntu series
bootstrapping=1

dir_name="dotnet${dotnet}-${version}"
tarball_suffix=".tar.xz"

if [ "${bootstrapping}" -eq "1" ]; then
    tarball_name="dotnet${dotnet}_${version}.orig"
else
    tarball_name="dotnet${dotnet}_${version}~{arch}-bootstrap.orig"
fi

tarball="${tarball_name}${tarball_suffix}"

if [ -f "${tarball_name}${tarball_suffix}" ]; then
    echo "error: ${tarball_name}${tarball_suffix} already exists"
    exit 1
fi

# The below code avoids download the tarball if it has happened before
# sha512 has to be manually calculated on a single download and updated for every microrelease
# or provided by upstream.
download_mstarball=0
if [ -s "${ms_tarball}" ]; then
  sha512="600bbcab046e3073d2b445d29de569c3415615699eb6c4296975aa9e8e1b3347fc9d6272acc269395e2a1ff1bec6273c0bd4d8d99c52147dd313a33b8577a729"
  existing_sha512sum=$(sha512sum "${ms_tarball}" | cut -d' ' -f1)
  if [ "${sha512}" == "${existing_sha512sum}" ]; then
     download_mstarball=1
  else
     rm "{ms_tarball}"
  fi
fi

download_OK=1
if [ "$download_mstarball" -eq "0" ]; then
    wget "${link}" -O "${ms_tarball}"
    download_OK=$?
fi

# Clean the tarball
if [ "${download_OK}" -eq "0" ] || [ "${download_mstarball}" -eq "1" ]; then

    if [ -d "${dir_name}" ]; then
    	rm -rf "${dir_name}"
    fi

    mkdir ${dir_name}
    pushd ${dir_name}
    tar xvzf ../${ms_tarball}


    if [ "$bootstrapping" -eq "0" ]; then
       ./prep.sh --bootstrap
    fi

    # Remove files with funny licenses, crypto implementations and other
    # not-very-useful artifacts to reduce tarball size
    # This list concords with the File-Excluded stanza in the copyright

    # Binaries for gradle
    rm -r src/aspnetcore/src/SignalR/clients/java/signalr/gradle*

    # Unnecessary crypto implementation: IDEA
    rm -r src/runtime/src/tests/JIT/Performance/CodeQuality/Bytemark/

    # https://github.com/dotnet/aspnetcore/issues/34785
    find src/aspnetcore/src -type d -name samples -print0 | xargs -0 rm -r

    # https://github.com/NuGet/Home/issues/11094
    rm -r src/nuget-client/test/EndToEnd

    #Checked that are not needed in the build: this only removes under roslyn:
    #src/roslyn/src/Compilers/Test/Resources/Core/SymbolsTests/V?/*.dll
    find src/roslyn/src/Compilers/Test/Resources -iname "*.dll" -exec rm -rf {} +

    # https://github.com/microsoft/ApplicationInsights-dotnet/issues/2670
    #we are applying a patch for this
    #rm -r src/source-build-externals/src/application-insights/LOGGING/test/Shared/CustomTelemetryChannel.cs

    #Don't remove vendorized libunwind because we need it for arm64 archs
    #rm -r src/runtime/src/coreclr/pal/src/libunwind

    #CPC-1578 prebuilts not used in build
    rm src/roslyn/src/Compilers/Test/Resources/Core/DiagnosticTests/ErrTestMod01.netmodule
    rm src/roslyn/src/Compilers/Test/Resources/Core/DiagnosticTests/ErrTestMod02.netmodule
    rm src/roslyn/src/Compilers/Test/Resources/Core/ExpressionCompiler/LibraryA.winmd
    rm src/roslyn/src/Compilers/Test/Resources/Core/ExpressionCompiler/LibraryB.winmd
    rm src/roslyn/src/Compilers/Test/Resources/Core/ExpressionCompiler/Windows.Data.winmd
    rm src/roslyn/src/Compilers/Test/Resources/Core/ExpressionCompiler/Windows.Storage.winmd
    rm src/roslyn/src/Compilers/Test/Resources/Core/ExpressionCompiler/Windows.winmd
    rm src/roslyn/src/Compilers/Test/Resources/Core/MetadataTests/Invalid/EmptyModuleTable.netmodule
    rm src/roslyn/src/Compilers/Test/Resources/Core/MetadataTests/NetModule01/ModuleCS00.mod
    rm src/roslyn/src/Compilers/Test/Resources/Core/MetadataTests/NetModule01/ModuleCS01.mod
    rm src/roslyn/src/Compilers/Test/Resources/Core/MetadataTests/NetModule01/ModuleVB01.mod
    rm src/roslyn/src/Compilers/Test/Resources/Core/SymbolsTests/CustomModifiers/Modifiers.netmodule
    rm src/roslyn/src/Compilers/Test/Resources/Core/SymbolsTests/MultiModule/mod2.netmodule
    rm src/roslyn/src/Compilers/Test/Resources/Core/SymbolsTests/MultiModule/mod3.netmodule
    rm src/roslyn/src/Compilers/Test/Resources/Core/SymbolsTests/MultiTargeting/Source1Module.netmodule
    rm src/roslyn/src/Compilers/Test/Resources/Core/SymbolsTests/MultiTargeting/Source3Module.netmodule
    rm src/roslyn/src/Compilers/Test/Resources/Core/SymbolsTests/MultiTargeting/Source4Module.netmodule
    rm src/roslyn/src/Compilers/Test/Resources/Core/SymbolsTests/MultiTargeting/Source5Module.netmodule
    rm src/roslyn/src/Compilers/Test/Resources/Core/SymbolsTests/MultiTargeting/Source7Module.netmodule
    rm src/roslyn/src/Compilers/Test/Resources/Core/SymbolsTests/RetargetingCycle/V1/ClassB.netmodule
    rm src/roslyn/src/Compilers/Test/Resources/Core/SymbolsTests/TypeForwarders/Forwarded.netmodule
    rm src/roslyn/src/Compilers/Test/Resources/Core/SymbolsTests/V1/MTTestModule1.netmodule
    rm src/roslyn/src/Compilers/Test/Resources/Core/SymbolsTests/V1/MTTestModule2.netmodule
    rm src/roslyn/src/Compilers/Test/Resources/Core/SymbolsTests/V2/MTTestModule1.netmodule
    rm src/roslyn/src/Compilers/Test/Resources/Core/SymbolsTests/V2/MTTestModule3.netmodule
    rm src/roslyn/src/Compilers/Test/Resources/Core/SymbolsTests/V3/MTTestModule1.netmodule
    rm src/roslyn/src/Compilers/Test/Resources/Core/SymbolsTests/V3/MTTestModule4.netmodule
    rm 'src/roslyn/src/Compilers/Test/Resources/Core/SymbolsTests/With Spaces.netmodule'
    rm src/roslyn/src/Compilers/Test/Resources/Core/SymbolsTests/netModule/CrossRefModule1.netmodule
    rm src/roslyn/src/Compilers/Test/Resources/Core/SymbolsTests/netModule/CrossRefModule2.netmodule
    rm src/roslyn/src/Compilers/Test/Resources/Core/SymbolsTests/netModule/hash_module.netmodule
    rm src/roslyn/src/Compilers/Test/Resources/Core/SymbolsTests/netModule/netModule1.netmodule
    rm src/roslyn/src/Compilers/Test/Resources/Core/SymbolsTests/netModule/netModule2.netmodule
    rm src/roslyn/src/Compilers/Test/Resources/Core/WinRt/W1.winmd
    rm src/roslyn/src/Compilers/Test/Resources/Core/WinRt/W2.winmd
    rm src/roslyn/src/Compilers/Test/Resources/Core/WinRt/WB.winmd
    rm src/roslyn/src/Compilers/Test/Resources/Core/WinRt/WB_Version1.winmd
    rm src/roslyn/src/Compilers/Test/Resources/Core/WinRt/WImpl.winmd
    rm src/roslyn/src/Compilers/Test/Resources/Core/WinRt/WinMDPrefixing.winmd
    rm src/roslyn/src/Compilers/Test/Resources/Core/WinRt/Windows.Languages.WinRTTest.winmd
    rm src/roslyn/src/Compilers/Test/Resources/Core/WinRt/Windows.winmd
    rm src/roslyn/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/Resources/WindowsProxy.winmd
    rm src/runtime/src/libraries/System.Reflection.Metadata/tests/Resources/NetModule/ModuleCS00.mod
    rm src/runtime/src/libraries/System.Reflection.Metadata/tests/Resources/NetModule/ModuleCS01.mod
    rm src/runtime/src/libraries/System.Reflection.Metadata/tests/Resources/NetModule/ModuleVB01.mod
    rm src/runtime/src/libraries/System.Reflection.Metadata/tests/Resources/WinRT/Lib.winmd
    rm src/linker/external/cecil/Test/Resources/assemblies/ManagedWinmd.winmd
    rm src/linker/external/cecil/Test/Resources/assemblies/NativeWinmd.winmd
    rm src/linker/external/cecil/Test/Resources/assemblies/moda.netmodule
    rm src/linker/external/cecil/Test/Resources/assemblies/modb.netmodule
    rm src/linker/external/cecil/Test/Resources/assemblies/winrtcomp.winmd

    popd
else
    echo "An error ocurred when downloading MS tarball"
    exit 1
fi

tar -I 'xz -T 0' -cf "${tarball}" "${dir_name}"
rm "${ms_tarball}"
