#!/bin/bash

# We want to catch any command failure, and exit immediately
set -e

# Download helper for git
# Call it with:
#   $1: git repo
#   $2: git cset
#   $3: package's basename (eg. foobar-1.2.3)
#   $4: output file
# And this environment:
#   GIT      : the git command to call
#   BUILD_DIR: path to Buildroot's build dir

repo="${1}"
cset="${2}"
basename="${3}"
output="${4}"

repodir="${basename}.tmp-git-checkout"
tmp_tar="$( mktemp "${BUILD_DIR}/.XXXXXX" )"
tmp_output="$( mktemp "${output}.XXXXXX" )"

# Play tic-tac-toe with temp files
# - first, we download to a trashable location (the build-dir)
# - then we create the uncomporessed tarball in tht same trashable location
# - then we create a temporary compressed tarball in the final location, so
#   it is on the same filesystem as the final file
# - finally, we atomically rename to the final file

cd "${BUILD_DIR}"
# Remove leftovers from a previous failed run
rm -rf "${repodir}"

git_done=0
if [ -n "$(${GIT} ls-remote "${repo}" "${cset}" 2>&1)" ]; then
    printf "Doing shallow clone\n"
    if ${GIT} clone --depth 1 -b "${cset}" --bare "${repo}" "${repodir}"; then
        git_done=1
    fi
fi
if [ ${git_done} -eq 0 ]; then
    printf "Doing full clone\n"
    ${GIT} clone --bare "${repo}" "${repodir}"
fi

ret=1
pushd "${repodir}" >/dev/null
if ${GIT} archive --prefix="${basename}/" -o "${tmp_tar}" \
                  --format=tar "${cset}"; then
    if gzip -c "${tmp_tar}" >"${tmp_output}"; then
        mv "${tmp_output}" "${output}"
        ret=0
    fi
fi
popd >/dev/null

rm -rf "${repodir}" "${tmp_tar}" "${tmp_output}"
exit ${ret}
