#!/bin/bash
#
#  mkpkgs
# 
#  Copyright (C) 2010-2012 James Mills
# 
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 
#  USA.
#

VERSION="0.1"

test_application () {
    application=${1}
    $application --version &> /dev/null
    if [[ $? != 0 ]]; then
        echo "Cannot find or execute ${application}!"
        exit 1
    fi
}

get_latest_tag() {
    echo "$(hg tags | awk '{if (NR == 2) print $1}')"
}

make_packages() {
    cwd=$(pwd)
    hg=$(which hg)
	python=$(which ${1})

    test_application "$hg"
    test_application "$python"

    status=$(hg status -0 -m)
    if [[ $status ]]; then
        echo "Working directory not in a clean state! Aborting..."
        exit 2
    fi

    echo "Building packages for $python ..."

    tag=$(get_latest_tag)

    $hg update -C ${tag} &> /dev/null

    $python setup.py clean &> /dev/null
    $python setup.py build &> /dev/null
    $python setup.py bdist_egg &> /dev/null
    $python setup.py sdist --formats=bztar,gztar,zip &> /dev/null

    $hg update -C &> /dev/null
}

print_help() {
	echo "usage: $COMMAND [options] machines"
	echo "options:"
	echo "   -p=PYTHON  specify python binary to use"
	echo "   -v         print version and exit"
	echo "   -h         print help and exit"
}

parse_options() {
	PYTHON="python2.6"

	while getopts "p:vh-" OPT ; do
		case $OPT in
			p)
				PYTHON="$OPTARG" ;;
			v)
				echo "$COMMAND $VERSION"
				exit 0 ;;
			h)
				print_help
				exit 0 ;;
		esac
	done

	shift $(($OPTIND - 1))
}

main() {
	parse_options "$@"

    make_packages "$PYTHON"
}

### Main

COMMAND=$(basename $0)

main "$@"

#n End of File
