#!/bin/sh

error() {
    echo "$*" 1>&2
}

usage() {
	cat >/dev/stderr <<EOF

usage: $0 <tag>

	updates the missing sources from the giada tarball

	this is done via a git checkout, so you must provide the
        git tag (or other ref).

	the Debian package version is "${pkgversion}"


EOF
exit $1
}

trytwice() {
    "$@" || (sleep 2 && "$@")
}

deps() {
	cat <<EOF
geompp
mcl-atomic-swapper
mcl-audio-buffer
mcl-utils
EOF
}

srcdir="$(cd "${0%/*}"; pwd)"
pkgdir="$(cd "${srcdir}/../.."; pwd)"
pkgversion="$(cd "${pkgdir}"; dpkg-parsechangelog -SVersion)"

workdir=$(mktemp -d)
#trap 'rm -rf "${workdir}"' EXIT INT TERM

tag="$1"

if [ -z "${tag}" ]; then
	usage 1
fi


trytwice git clone --revision="${tag}" --depth 1 https://github.com/monocasual/giada.git "${workdir}/giada"
trytwice git -C "${workdir}/giada" submodule update --init

deps | while read dep; do
    depdir="${srcdir}/${dep}"
    if ! test -d "${workdir}/giada/src/deps/${dep}/src"; then
        error "skipping ${dep}"
        continue
    fi
    rm -rf "${depdir}"
    cp -rav "${workdir}/giada/src/deps/${dep}/src" "${depdir}"
done
