#!/bin/sh

set -e

# Test the fallback path of pkgos-debcrate: when the upstream repository
# cannot be cloned, the crate archive is imported into a fresh git
# repository, tagged with the upstream version, branched to
# debian/unstable, with the debian folder committed as "Initial
# packaging".

ME=$(basename $0)
WORK=$(mktemp -d)
trap 'rm -rf "${WORK}"' EXIT

TESTDIR=$(cd "$(dirname "$0")" && pwd)
. "${TESTDIR}/fixtures.sh"

cd "${WORK}"

SERDE_REQ=1 NIX_REQ=0.30 fixture_cargo_toml ${WORK}/Cargo.toml
FIX_REPO=https://example.com/does-not-exist/serde-test fixture_pack_crate ${WORK} ${WORK}/Cargo.toml
mock_git_fail ${WORK}

cat >${WORK}/policy.txt <<EOF
librust-serde-dev=1.0.200
librust-serde-json-dev=1.0.140
librust-tokio-dev=1.53.1
librust-tempfile-dev=3.20.0
librust-cc-dev=1.2.0
librust-nix-dev=0.30.1
EOF

mock_apt ${WORK} ${WORK}/policy.txt
debcrate_env ${WORK}

"${SCRIPT}" serde_test >${WORK}/out.log 2>&1 || {
	cat ${WORK}/out.log
	echo "${ME}: pkgos-debcrate failed"
	exit 1
}

check () {
	if ! grep -q "$2" "$1" ; then
		echo "${ME}: $1 doesn't contain: $2"
		exit 1
	fi
}

check ${WORK}/out.log 'Could not clone the upstream repository'

if [ -d ${WORK}/rust-serde-test ] ; then
	echo "${ME}: a clone directory shouldn't have been created"
	exit 1
fi

PKGDIR=${WORK}/rust-serde-test-0.1.0
cd ${PKGDIR}
if [ -z "$(git tag --list 0.1.0)" ] ; then
	echo "${ME}: upstream git tag 0.1.0 is missing"
	exit 1
fi
if [ "$(git branch --show-current)" != "debian/unstable" ] ; then
	echo "${ME}: debian/unstable branch is missing or not checked out"
	exit 1
fi
if ! git log --format=%s | grep -qx 'Imported upstream version 0.1.0' ; then
	echo "${ME}: the upstream import commit is missing"
	exit 1
fi
if [ "$(git log --format=%s -1)" != "Initial packaging" ] ; then
	echo "${ME}: last commit isn't 'Initial packaging'"
	exit 1
fi
cd ${WORK}

exit 0
