#!/bin/bash
#
# Build an open-iscsi source rpm
#
# To Do:
# - add "verbose" mode
# - use getopt for option handling
#

if ! which git > /dev/null ; then
    echo "git not found, cannot continue"
    exit 1
fi

RPM="open-iscsi"
BRANCH=$(git rev-parse --abbrev-ref HEAD)
VERSION="2.1.9-suse"
DESTDIR=
TMPDIR=


while [ $# -gt 0 ] ; do
    case "$1" in
	-c|--clean)
	    remove_destdir=1
	    shift
	    ;;
        -d)
            DESTDIR="$2"
            shift 2
            ;;
        --destdir*)
            DESTDIR="${$1#*=}"
            shift
            ;;
        -b)
            BRANCH="$2"
            shift 2
            ;;
        --branch=*)
            BRANCH="${1##*=}"
            shift
            ;;
        -f|--force)
            force=1
	    update=
            shift;
            ;;
        -u|--update)
            update=1
	    force=
            shift
            ;;
        *)
            echo "Usage: build_rpm [-c|-f|-u] [-d dir|--destdir=DIR] " \
                 "[-b BRANCH|--branch=BRANCH]"
            exit 1
            ;;
    esac
done

if [ -d "$DESTDIR" ] ; then
    if [ -z "$force" ] && [ -z "$update" ] ; then
        echo "directory $DESTDIR exists, cannot continue"
        exit 1
    elif [ -z "$update" ] ; then
        if ! rm -rf "$DESTDIR" ; then
            echo "Cannot remove directory $DESTDIR"
            exit 1
        fi
	mkdir -p "$DESTDIR"
    fi
elif [ -n "$DESTDIR" ] ; then
    mkdir -p "$DESTDIR"
else
    DESTDIR=$(mktemp -d --tmpdir $RPM-XXXXXXXX)
    if [ ! -d "$DESTDIR" ] ; then
	echo "Cannot create directory $DESTDIR"
	exit 1
    fi
fi

#
# to be able to convert this git archive into the proper format
# for package building, we want a spec file, a changes file,
# a base tar file, and zero or more patch files
#

# create the spec and changes files -- Note that this
# gets the HEAD of these files from the specified branch,
# not from the current workspace
git show $BRANCH:rpm/$RPM.spec > $DESTDIR/$RPM.spec
git show $BRANCH:rpm/$RPM.changes > $DESTDIR/$RPM.changes

# create the base tar file containing the open-iscsi base code
git archive --format=tar --prefix=$RPM-$VERSION/ --worktree-attributes "$VERSION" \
    | bzip2 > $DESTDIR/$RPM-$VERSION.tar.bz2

# patch: create a diff file for changes between the base version
# and the update tag if there are any differences
files_changed=$(git diff --name-only --diff-filter=d ${VERSION}..${BRANCH}|grep -v '^rpm/')
if [[ -z $files_changed ]] ; then
	# no changes except rpm/ subdir changes, so create an empty changes file
	bzip2 < /dev/null > $DESTDIR/$RPM-SUSE-latest.diff.bz2
else
	git diff ${VERSION}..${BRANCH} $files_changed | \
		bzip2 > $DESTDIR/$RPM-SUSE-latest.diff.bz2
fi

echo "$RPM src RPMs copied to $DESTDIR"

if [ -n "$remove_destdir" ] ; then
    rm -rf $DESTDIR
    if [ "$TMPDIR" ] ; then
	rm -rf $TMPDIR
    fi
fi
