#!/usr/bin/env bash
set -ex

# Determine where "../dist" is
DIST_DIR="${1:-dist}"
if which gmktemp > /dev/null 2>&1
then
    # For Darwin
    MKTEMP=gmktemp
else
    MKTEMP=mktemp
fi
BUILD_DIR=$($MKTEMP --directory --tmpdir=$PWD build-dist-tmp-XXXXXX)
mkdir -p "$BUILD_DIR"

build_script=$(cat <<'EOF'
set -ex

# Build linux wheels from the source distribution we created
for PYBIN in /opt/python/*/bin;
do
  "${PYBIN}/pip" wheel --no-deps /dd-trace-py/*.tar.gz -w /dd-trace-py
done

# Build manylinux wheels from the linux wheels we just created
for whl in /dd-trace-py/*-linux_${ARCH}.whl;
do
  auditwheel repair "${whl}" -w /dd-trace-py

  # Remove linux wheel since we only want the manylinux wheels
  rm "${whl}"
done
EOF
)

# First build a source distribution for our package
python setup.py sdist --dist-dir "$BUILD_DIR"

# Build x86_64 linux and manylinux wheels
docker run --rm -v "${BUILD_DIR}:/dd-trace-py" -e "ARCH=x86_64" quay.io/pypa/manylinux1_x86_64 /bin/bash -c "${build_script}"

# Build i686 linux and manylinux wheels
docker run --rm -v "${BUILD_DIR}:/dd-trace-py" -e "ARCH=i686" quay.io/pypa/manylinux1_i686 linux32 /bin/bash -c "${build_script}"

test -e "$DIST_DIR" || mkdir "$DIST_DIR"
mv "$BUILD_DIR"/* "$DIST_DIR"
rmdir "$BUILD_DIR"
