#!/bin/bash

set -e

here=$(dirname $(realpath "$0" 2> /dev/null || grealpath "$0"))
. "$here"/base.sh || (echo "Could not source contrib/base.sh" && exit 1)

# Use secp256k1 from the monorepo by default, unless USE_SECP256K1_GITHUB is set by env.
if [ -n "${USE_SECP256K1_GITHUB}" ]; then
    warn "Building secp256k1 using the Github repo"
    setup_pkg "secp256k1" "${SECP256K1_GITHUB_REPO}" "master"
else
    info "Building secp256k1 from the monorepo"
    setup_secp_from_monorepo
fi

if ! [ -x configure ] ; then
    echo "LDFLAGS = -no-undefined" >> Makefile.am
    ./autogen.sh || fail "Could not run autogen for $pkgname. Please make sure you have automake and libtool installed, and try again."
fi
if ! [ -r config.status ] ; then
    ./configure \
        $AUTOCONF_FLAGS \
        --prefix="$pkgbuilddir/dist" \
        --enable-module-recovery \
        --enable-experimental \
        --enable-module-ecdh \
        --enable-module-schnorr \
        --disable-module-schnorrsig \
        --disable-tests \
        --disable-static \
        --enable-shared || fail "Could not configure $pkgname. Please make sure you have a C compiler installed and try again."
fi
make -j$WORKER_COUNT || fail "Could not build $pkgname"
make install || fail "Could not install $pkgname"
. "$pkgbuilddir/dist/lib/libsecp256k1.la"
host_strip "$pkgbuilddir/dist/lib/$dlname"
cp -fpv "$pkgbuilddir/dist/lib/$dlname" "$here/../electrumabc/." || fail "Could not copy the $pkgname binary to its destination"
info "$dlname has been placed in the 'electrumabc' folder."
popd_pkg
rm -Rf "$pkgbuilddir"
