#!/bin/sh -e
#
# Generate a tarball for a release

bzr=${BZR:-"brz"}

usage()
{
	cat <<_EOF_
Usage: $0 <version> [<revspec>]
   e.g:
     $0 1.2.3 -r1.2.3
     $0 current
_EOF_
	exit 0
}

# Get args
if [ $# -lt 1 -o $# -gt 2 ]; then usage; fi
version=$1
rev=${2:-"-1"}



# Be in the tree root
rtdir=`${bzr} root $0`
cd $rtdir

# Setup locations and check stuff
bname="freebsd-rustdate-${version}"
if [ -r $rtdir/$bname.tar ] ; then
	echo "Tarball '$bname.tar' exists!"
	exit 1
fi
if [ -r $rtdir/$bname.tar.xz ] ; then
	echo "Tarball '$bname.tar.xz' exists!"
	exit 1
fi

tmpdir=`mktemp -d "${rtdir}/frup-mktar.XXXXXX"`
bdir="${tmpdir}/${bname}"
if [ -d ${bdir} ] ; then
	echo "Dir '$dir' exists!"
	exit 1
fi

# Put appropriate files in it
echo "Exporting into ${bdir}"
${bzr} export -r${rev} ${bdir}

# Build Cargo.lock
echo "Generate Cargo.lock"
( cd $bdir && cargo generate-lockfile)

# Do a build and test, just to be sure things are OK
echo "Testing"
(
	cd $bdir
	cargo test -q || exit 1
)

# Generate the shell complation files
# We probably don't need to actually ship these, since users who care can
# generate them.  And so can the port, which is what people will
# presumably generally be using...
# echo "Generating completion"
# (
# 	cd $bdir
# 	mkdir completion
# 	for sh in bash fish zsh; do
# 		cargo run -q -- complete -s ${sh} > completion/${sh}
# 	done
# )

# Cleanup target dir we (may have) just made
echo "Cleanup target"
( cd $bdir && rm -rf target )

# Make the tar
echo "Making tarball"
(
	cd $tmpdir
	tar \
		--uid 0 --uname root \
		--gid 0 --gname wheel \
		-cvf ${rtdir}/${bname}.tar ${bname}
)

# Cleanup and display
rm -rf ${tmpdir}
ls -l ${bname}.tar
