using BinaryProvider, Libdl

# 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")))
products = [
    LibraryProduct(prefix, String["libmbedcrypto"], :libmbedcrypto),
    LibraryProduct(prefix, String["libmbedx509"], :libmbedx509),
    LibraryProduct(prefix, String["libmbedtls"], :libmbedtls),
]

const juliaprefix = joinpath(Sys.BINDIR, "..")

juliaproducts = Product[
    LibraryProduct(juliaprefix, "libmbedcrypto", :libmbedcrypto),
    LibraryProduct(juliaprefix, "libmbedx509", :libmbedx509),
    LibraryProduct(juliaprefix, "libmbedtls", :libmbedtls)
]

# Download binaries from hosted location
bin_prefix = "https://github.com/JuliaWeb/MbedTLSBuilder/releases/download/v0.17.0"

# Listing of files generated by BinaryBuilder:
download_info = Dict(
    Linux(:aarch64, libc=:glibc) => ("$bin_prefix/MbedTLS.v2.16.0.aarch64-linux-gnu.tar.gz", "aeaaabcef59f4587bbd003a3cb891d85e9d723cba641fd004bc3273bf574dad5"),
    Linux(:aarch64, libc=:musl) => ("$bin_prefix/MbedTLS.v2.16.0.aarch64-linux-musl.tar.gz", "dcc4c21affc2e687ae43bac42ff9481a70e9824fc08518987b805b9e318f0068"),
    Linux(:armv7l, libc=:glibc, call_abi=:eabihf) => ("$bin_prefix/MbedTLS.v2.16.0.arm-linux-gnueabihf.tar.gz", "48cd2b4cbd9b2f4a7ab2f1060a240b1170b5807af236777602cd331c6b29c037"),
    Linux(:armv7l, libc=:musl, call_abi=:eabihf) => ("$bin_prefix/MbedTLS.v2.16.0.arm-linux-musleabihf.tar.gz", "25003edb6fb346e4cd299c30b7660f6abb8e493df75fa224951d252cee4b5e28"),
    Linux(:i686, libc=:glibc) => ("$bin_prefix/MbedTLS.v2.16.0.i686-linux-gnu.tar.gz", "113d3e8220ea24d2e075623cebcb2e0a1864bada52d5d9065cddc7b04ed24f1c"),
    Linux(:i686, libc=:musl) => ("$bin_prefix/MbedTLS.v2.16.0.i686-linux-musl.tar.gz", "48531771fcfb69cbc79abde1c06ac74e5e5d9e24367a111eac6cbfe42e5377c8"),
    Windows(:i686) => ("$bin_prefix/MbedTLS.v2.16.0.i686-w64-mingw32.tar.gz", "5be5cae452e513780380f276a19f2cd5eecbecad01728fd180b1c19022369e96"),
    Linux(:powerpc64le, libc=:glibc) => ("$bin_prefix/MbedTLS.v2.16.0.powerpc64le-linux-gnu.tar.gz", "d07a85c710a82bd7ab0d9eabb469e378ce31083161ff864f157962ec018db4e2"),
    MacOS(:x86_64) => ("$bin_prefix/MbedTLS.v2.16.0.x86_64-apple-darwin14.tar.gz", "8939d8b39618d9206feac886298070f5519ab13ac190b44d99da5e62b3d5fef1"),
    Linux(:x86_64, libc=:glibc) => ("$bin_prefix/MbedTLS.v2.16.0.x86_64-linux-gnu.tar.gz", "f8985d86a78e03c7b7cd169c664b93ebe9eb726c652be7bb96707810b0c68bbf"),
    Linux(:x86_64, libc=:musl) => ("$bin_prefix/MbedTLS.v2.16.0.x86_64-linux-musl.tar.gz", "e9a254ff953899f79b79af8f30f9a95f0acc21f44d5a3cf683cfc19b1fb21808"),
    FreeBSD(:x86_64) => ("$bin_prefix/MbedTLS.v2.16.0.x86_64-unknown-freebsd11.1.tar.gz", "8c923544323c6009a46a70cedf7fb714c5d9e0f23650c2ef8b151a84bf74f527"),
    Windows(:x86_64) => ("$bin_prefix/MbedTLS.v2.16.0.x86_64-w64-mingw32.tar.gz", "85b95b43014fc8370c3dd8b41f341c6849fcde12e321c24faa8a86193161252e"),
)

# First, check to see if we're all satisfied
gpl = haskey(ENV, "USE_GPL_MBEDTLS")
forcebuild = parse(Bool, get(ENV, "FORCE_BUILD", "false")) || gpl
done = false
if any(!satisfied(p; verbose=verbose) for p in products) || forcebuild
    if haskey(download_info, platform_key()) && !forcebuild
        # Download and install binaries
        url, tarball_hash = download_info[platform_key()]
        install(url, tarball_hash; prefix=prefix, force=true, verbose=verbose)
        done = all(satisfied(p; verbose=verbose) for p in products)
        done && @info "using prebuilt binaries"
    end
    if !done && all(satisfied(p; verbose=verbose) for p in juliaproducts) && !forcebuild
        @info "using julia-shippied binaries"
        products = juliaproducts
    elseif !done || forcebuild
        @info "attempting source build"
        VERSION = "2.16.0"
        url, hash = haskey(ENV, "USE_GPL_MBEDTLS") ?
            ("https://tls.mbed.org/download/mbedtls-$VERSION-gpl.tgz", "c8d7a4696287cb9533c455bdd65859106dbdd4472c125194387486e6d4df2799") :
            ("https://tls.mbed.org/download/mbedtls-$VERSION-apache.tgz", "e3dab56e9093c790b7d5e0f7eb19451010fe680649d25cf1dcca9d5441669ae2")
        download_verify(url, hash, joinpath(@__DIR__, "mbedtls.tgz"), force=true, verbose=true)
        unpack(joinpath(@__DIR__, "mbedtls.tgz"), @__DIR__; verbose=true)
        withenv("VERSION"=>VERSION) do
            run(Cmd(`./build.sh`, dir=@__DIR__))
        end
        if any(!satisfied(p; verbose=verbose) for p in products)
            error("attempted to build mbedtls shared libraries, but they couldn't be located (deps/usr/lib)")
        end
    end
end

write_deps_file(joinpath(@__DIR__, "deps.jl"), products, verbose=verbose)
