#!/bin/sh
# This file is part of curtin. See LICENSE file for copyright and license info.

set -eu

sourcename="curtin"
TEMP_D=""
UNCOMMITTED=${UNCOMMITTED:-0}
RELEASE=${RELEASE:-UNRELEASED}

fail() { echo "$@" 1>&2; exit 1; }
cleanup() {
   [ -z "$TEMP_D" ] || rm -Rf "$TEMP_D"
}

if [ "${1:-}" = "-h" -o "${1:-}" = "--help" ]; then
   cat <<EOF
Usage: ${0##*/}
   build a deb of from trunk directory
   any options are passed straight through to debuild

   Example:
    * ${0##*/} -us -uc

   Its not significantly different than what you'd get by modifying
   the debian/changelog to have the current revno, and then running
     debuild --no-tgz-check
EOF
exit
fi

bname=${0##*/}

start_d=$PWD
top_d=$(cd "$(dirname "${0}")"/.. && pwd)
ref=HEAD

if [ $# -eq 0 ]; then
   # if no opts given, build source, without depends.
   set -- -S -d
fi

# uver gets 17.1-3-gc85e2562 '17.1' if this is a tag.
uver=$(git describe --long --abbrev=8 "--match=[0-9][0-9]*" "$ref")
clogver_new="${uver}-0ubuntu1"

# uver_base_rel rel gets '17.1'
uver_base_rel=${uver%%-*}
if [ "${uver_base_rel}" = "${uver}" ]; then
   echo "building from a tagged version ($uver)" 1>&2
fi

TEMP_D=$(mktemp -d "${TMPDIR:-/tmp}/${bname}.XXXXXX")

trap cleanup EXIT

echo "building version ${uver}"

dir="${sourcename}-$uver"
tarball="${sourcename}_$uver.orig.tar.gz"

myd=$(dirname "$0")
"$myd/make-tarball" --output="$TEMP_D/$tarball" --long "$ref"
echo "created ${tarball}"

cd "${TEMP_D}"
tar xzf "$tarball" || fail "failed extract tarball"

if [ ! -d "$dir" ]; then
    echo "did not find a directory created by make-tarball. sorry." 1>&2
    exit
fi
cd "$dir" || fail "failed cd $dir"

dch --create --package curtin --newversion "$clogver_new" \
    --distribution "$RELEASE" "Development release"
debuild "$@" || fail "debuild failed"

cd "$TEMP_D"
for f in *; do
   [ -f "$f" ] || continue
   cp "$f" "$start_d" || fail "failed copy $f"
   echo "wrote $f"
done
exit

# vi: ts=4 expandtab syntax=sh
