#!/bin/bash

usage() {
cat << EOF

        Usage: $0 repo daily | release

        repo            - git repository
        daily           - repo-ver-rel.g<short_commit_ref>.tar.gz will be created
        release         - repo-ver-rel.tar.gz will be created

EOF
}

# Execute command w/ echo and exit if it fail
ex()
{
	echo "$@"
	if ! eval "$@"; then
		printf "\nFailed executing $@\n"
		exit 1
	fi
}

setlocalversion()
{
	# Check for git and a git repo.
	if head=`git rev-parse --verify --short HEAD 2>/dev/null`; then
	
		# If we are at a tagged commit (like "v2.6.30-rc6"), we ignore it,
		# because this version is defined in the top level Makefile.
		if [ -z "`git describe --exact-match 2>/dev/null`" ]; then
	
			# If we are past a tagged commit (like "v2.6.30-rc5-302-g72357d5"),
			# we pretty print it.
			if atag="`git describe 2>/dev/null`"; then
				echo "$atag" | awk -F- '{printf(".%s", $(NF))}'
	
			# If we don't have a tag at all we print -g{commitish}.
			else
				printf '%s%s' .g $head
			fi
		fi
	
		# Is this git on svn?
		if git config --get svn-remote.svn.url >/dev/null; then
		        printf -- '.svn%s' "`git svn find-rev $head`"
		fi
	
		# Are there uncommitted changes?
		git update-index --refresh --unmerged > /dev/null
		if git diff-index --name-only HEAD | grep -v "^scripts/package" \
		    | read dummy; then
			printf '%s' .dirty
		fi
	
		# All done with git
		exit
	fi
	
	# Check for svn and a svn repo.
	if rev=`svn info 2>/dev/null | grep '^Last Changed Rev'`; then
		rev=`echo $rev | awk '{print $NF}'`
		printf -- '.svn%s' "$rev"
	
		# All done with svn
		exit
	fi
}

URL="http://www.openfabrics.org/downloads"

if [ -z "$1" -o -z "$2" ]; then usage; exit 1; fi

if [ ! -d "$1" ]; then usage; exit 1; fi

NAME=$1
# ORIG_NAME used for packages that require different version for the same package, like dapl
ORIG_NAME=$NAME
TMPDIR=dist
TOPDIR=${PWD}/topdir

if [ ! -d $TMPDIR ]; then mkdir $TMPDIR; fi
if [ ! -d $TOPDIR ]; then mkdir -p $TOPDIR/{BUILD,BUILDS,RPMS,SOURCES,SPECS,SRPMS}; fi

if [ "$2" = "daily" -o "$2" = "release" ]; then
	if [ ! -f $TMPDIR/$NAME-$2.HEAD ]; then
		touch $TMPDIR/$NAME-$2.HEAD
	fi
	NEWHEAD=`cat $TMPDIR/$NAME-$2.HEAD`
else
	usage
	exit 1
fi

cd "$NAME"
echo "Updating git repo..."
git pull
RESULT=$?
HEAD=`git log --pretty=oneline -1`

ORIG_NAME=$NAME
case $NAME in
    dapl*)
    NAME=dapl
    ;;
    ibsim)
    VERSION=`sed -ne '/#define IBSIM_VERSION/s/^.*\"\(.*\)\".*$/\1/p' ibsim/ibsim.c`
    ;;
    qlvnictools)
    VERSION=0.0.1
    ;;
esac

if [ "$RESULT" -ne 0 ]; then
	echo "Failed to update the git repo cleanly, manual intervention required"
	exit 1
fi

if [ "$HEAD" = "$NEWHEAD" ] && [ "$2" != "release" ]; then
	echo "No new commits since last tarball creation, nothing to do."
	cd ..
	exit 0
fi

if [ -z ${VERSION} ]; then
	VERSION=`grep "AC_INIT.*$NAME" configure.in 2> /dev/null | cut -f 2 -d ',' | cut -f 1 -d '-' | sed -e 's/ //g;s/\[//g;s/\]//g'`
fi

if [ -z ${VERSION} ]; then
        VERSION=`grep "AM_INIT.*$NAME" configure.in 2> /dev/null | cut -f 2 -d ',' | cut -f 1 -d '-' | sed -e 's/ //g;s/(//g;s/)//g'`
fi

if [ -z ${VERSION} ] && [ -f ../$NAME/$NAME.spec ]; then
        VERSION=`grep "Version:" ../$NAME/$NAME.spec | awk '{print $NF}'`
fi

if [ -z ${VERSION} ]; then
        echo Cannot determine $NAME version
        exit 1
fi

if [ "$2" = "release" ]; then
	# Is the repo clean?
	git status | grep modified > /dev/null 2>&1
	if [ $? = 0 ]; then
		echo "There are modified files in the repo.  Please check any"
		echo "changes in before proceeding."
		exit 4
	fi
	
	if [ 1 -eq 0 ]; then
		# Since we will be tagging things, make sure we are on the right
		# branch
		git branch
		echo -n "Is the active branch the right one to tag this release on [y/N]? "
		read answer
		if [ "$answer" = y -o "$answer" = Y ]; then
			echo "Proceeding..."
		else
			echo "Please check out the right branch and run make.dist again"
			exit 0
		fi
	fi

	# Check versions to make sure that we can proceed
	TARBALL=$NAME-$VERSION.tar.gz
	if [ -f ../$TMPDIR/$TARBALL ]; then
		/bin/rm -f ../$TMPDIR/$TARBALL
	fi
	if [ 1 -eq 0 ]; then
		if [ ! -z "`git tag -l $NAME-$VERSION`" ]; then
			echo "A git tag already exists for $NAME-$VERSION.  Please change the version"
			echo "of $NAME so a tag replacement won't occur."
			exit 3
		fi
	fi
# On a real release, this resets the daily release starting point, on the
# assumption that any new daily builds will have a version number that is
# incrementally higher than the last officially released tarball.
	RELEASE=1
	echo $RELEASE > ../$TMPDIR/$NAME.release
else
	DATE=`date +%Y%m%d`
	if [ -f ../$TMPDIR/$NAME.release ]; then
		RELEASE=`cat ../$TMPDIR/$NAME.release`
		RELEASE=`expr $RELEASE + 1`
	else
		RELEASE=1
	fi
	echo $RELEASE > ../$TMPDIR/$NAME.release
	localversion=`setlocalversion`
	RELEASE=0.${RELEASE}${localversion}
	TARBALL=$NAME-${VERSION}-${RELEASE}.tar.gz
fi

cd ..
ex cp -a $ORIG_NAME $NAME-$VERSION

apply_patches()
{
        if [ -f fixes/series ]; then
            for pp in `cat fixes/series`
            do
                echo Applying fixes/$pp
                patch -p1 -l -i fixes/$pp
                if [ $? -ne 0 ]; then
                    echo Failed to apply fixes/$pp
                    exit 1
                fi
            done
        else
            for pp in `/bin/ls fixes/*.patch`
            do
                echo Applying $pp
                patch -p1 -l -i $pp
                if [ $? -ne 0 ]; then
                    echo Failed to apply $pp
                    exit 1
                fi
            done
        fi
        echo
        echo Patches for basename `basename $(pwd)` applied successfully
        echo
}

if [ -d $NAME-$VERSION/fixes ]; then
	cd $NAME-$VERSION
        # Apply patches from the fixes directory, if exist
        apply_patches
	cd ..
fi

if [ -f $NAME-$VERSION/autogen.sh ]; then
	cd $NAME-$VERSION
	bash ./autogen.sh
	cd ..
fi

if [ "$NAME" == "qlvnictools" ]; then
        cd $NAME-$VERSION/ibvexdmtools/
        bash ./autogen.sh
        cd -
fi

if [  -f $NAME-$VERSION/$NAME.spec.in ] && [ ! -f $NAME-$VERSION/$NAME.spec ]; then
        cp $NAME-$VERSION/$NAME.spec.in $NAME-$VERSION/$NAME.spec
elif [  -f $NAME-$VERSION/$NAME.spec ]; then
        echo "Using original spec"
else
        echo "RPM spec file is not found ???"
        exit 5
fi

perl -ni -e "s@(Version:).*@\$1 ${VERSION}@;s/\@VERSION\@/${VERSION}/;s@(Release:).*@\$1 ${RELEASE}@;s@(Source:).*@\$1 ${URL}/${TARBALL}@;s/\@RELEASE\@/\$1 ${RELEASE}/; print" $NAME-$VERSION/$NAME.spec

if [ "$NAME" == "opensm" ]; then
	perl -ni -e "s/\@OPENSM_CONFIG_SUB_DIR\@/opensm/; print" $NAME-$VERSION/$NAME.spec
fi

echo "Creating $TMPDIR/$TARBALL"
ex tar -czf $TMPDIR/$TARBALL --exclude=.git $NAME-$VERSION
echo "$HEAD" > $TMPDIR/$ORIG_NAME-$2.HEAD

ex mv $TMPDIR/$TARBALL $TOPDIR/SOURCES
rm -rf $NAME-$VERSION

echo
echo Created $TOPDIR/SOURCES/$TARBALL
echo
