#!/bin/bash
set -e

if ! which trollius2asyncio >/dev/null; then
    echo "trollius2asyncio not found. Install trollius-fixers." 1>&2
    exit 1
fi

for i in send/ recv/ test/test_send_ test/test_passthrough_ tools/recv_ tools/send_ tools/bench_; do
    src="spead2/${i}trollius.py"
    trg="spead2/${i}asyncio.py"
    echo "# Generated by bootstrap.sh from $src. Do not edit." > "$trg"
    echo >> "$trg"
    cat "$src" >> "$trg"
    trollius2asyncio -w -n --no-diffs "$trg"
    # trollius2asyncio doesn't rewrite internally references e.g
    # spead2.send.trollius to spead2.send.asyncio. This is a bit hacky but
    # easier than providing custom fixers and trying to bootstrap them.
    # Also we can't use -i because GNU sed and OS X sed have mutually
    # incompatible interpretations.
    sed 's/trollius/asyncio/g' "$trg" > "$trg.tmp"
    mv "$trg.tmp" "$trg"
    cat >> "$trg" <<EOF
# Monkey-patch asyncio.ensure_future for Python < 3.4.4.
if not hasattr(asyncio, 'ensure_future'):
    asyncio.ensure_future = getattr(asyncio, 'async')
EOF
done
python gen/gen_ibv_loader.py header > include/spead2/common_ibv_loader.h
python gen/gen_ibv_loader.py cxx > src/common_ibv_loader.cpp
autoreconf --install --force
