using BinaryProvider # requires BinaryProvider 0.3.0 or later
using Libdl: dlext

# Parse some basic command-line arguments
const verbose = "--verbose" in ARGS
const prefix = Prefix(get([a for a in ARGS if a != "--verbose"], 1, joinpath(@__DIR__, "usr")))
const LIBDIR = Sys.iswindows() ? Sys.BINDIR : joinpath(Sys.BINDIR, Base.LIBDIR)

const products = [
    LibraryProduct(LIBDIR, "librelic_gmp_pbc_bls381", :librelic_gmp_pbc_bls381),
    LibraryProduct(LIBDIR, "librelic_gmp_pbc_bn254", :librelic_gmp_pbc_bn254),
]

# Download binaries from hosted location
const version = "0.4.0-613-g613795f7-3"
const bin_prefix = "https://github.com/blenessy/RelicToolkitBuilder/releases/download/$version"

# Listing of files generated by BinaryBuilder:
const download_info = Dict(
    Linux(:i686, :glibc) => ("$bin_prefix/RelicToolkit.v$version.i686-linux-gnu.tar.gz", "e3019742022ba470fc8666fed87e510c55de2277932cb4c64dafab1915ff03e6"),
    Windows(:i686) => ("$bin_prefix/RelicToolkit.v$version.i686-w64-mingw32.tar.gz", "f60e0993059febdf7cf6b23121345e13a71aa5ffba0a391373c467aca94aac56"),
    MacOS(:x86_64) => ("$bin_prefix/RelicToolkit.v$version.x86_64-apple-darwin14.tar.gz", "60e2b5b7aacacad61d1fd18f476733fecb1749b23afb9ddafb5c8bd949e7681e"),
    Linux(:x86_64, :glibc) => ("$bin_prefix/RelicToolkit.v$version.x86_64-linux-gnu.tar.gz", "cd097d550e9a13ab4968f6f7b2d61a9bef291687d66833f248b1d9f3532e646d"),
    Windows(:x86_64) => ("$bin_prefix/RelicToolkit.v$version.x86_64-w64-mingw32.tar.gz", "83f17928a0d3fc7370d489a6787c0a77ec0f5d84fee73aa058d7e1e5cfa6c91b"),
)

# First, check to see if we're all satisfied
if any(!satisfied(p; verbose=verbose) for p in products)
    try
        # Download and install binaries
        url, tarball_hash = choose_download(download_info)
        install(url, tarball_hash; prefix=prefix, force=true, verbose=verbose)
        # The libs link towards libgmp-10.dll - this is an easy workaround
        if Sys.iswindows()
            cp(joinpath(LIBDIR, "libgmp.dll"), joinpath(Sys.BINDIR, "libgmp-10.dll"), force=true)
        end
        # Workaround: Copy libs to Sys.BINDIR to make the Windows libs work
        # tl;dr: there seems to bug when native libs depend on other native libs (libgmp-10.dll in our case)
        for p in products
            for n in p.libnames
                cp(joinpath(libdir(prefix), "$n.$dlext"), joinpath(LIBDIR, "$n.$dlext"), force=true)
            end
        end
    catch e
        if typeof(e) <: ArgumentError
            error("Your platform $(Sys.MACHINE) is not supported by this package!")
        else
            rethrow(e)
        end
    end
    # Finally, write out a deps.jl file
    write_deps_file(joinpath(@__DIR__, "deps.jl"), products, verbose=verbose)
end
