#!/bin/bash

TMP_DIR="$PWD/.tmp_dir"
ORIG_DIR="$PWD"

function cleanup {
    cd "$ORIG_DIR" || return
    rm -rf "$TMP_DIR"
}
trap cleanup EXIT

if ! test -d deciphon_sched; then
    echo "We are not at the root directory of the deciphon-sched project."
    exit 1
fi

echo
echo "Using directory \`$TMP_DIR\` to download deciphon-sched."

if test -d "$TMP_DIR"; then
    rm -rf "$TMP_DIR"
fi

mkdir "$TMP_DIR" || exit 1
cd "$TMP_DIR" || exit 1

USER=EBI-Metagenomics
PROJECT=deciphon-sched

echo -n "Fetching latest deciphon-sched version... "
VERSION=$(bash -c "$(curl -fsSL https://bit.ly/36UxPPz)" -s EBI-Metagenomics/deciphon-sched) || exit 1
echo " done."

TARFILE="$PROJECT-$VERSION.tar.gz"
TARURL="https://github.com/$USER/$PROJECT/archive/refs/tags/v$VERSION.tar.gz"

echo -n "Downloading $TARFILE... "
curl -o "$TARFILE" -L "$TARURL" --silent || exit 1
echo "done."

echo -n "Extracting $TARFILE... "
tar xzf "$TARFILE" || exit 1
echo "done."

echo -n "Merging headers into $output_dir/interface.h... "

output_dir="$ORIG_DIR/deciphon_sched"
cat "$output_dir/interface_preamble.h" >"$output_dir/interface.h"
echo "" >>"$output_dir/interface.h"

"$ORIG_DIR/tools/merge_headers" "${TARFILE%.tar.gz}/include/sched" >>"$output_dir/interface.h"

echo "done."
echo
