#!/bin/bash
# Sekati: Semantic Version String Manipulator
# @author jason m horwitz | sekati.com
# Copyright (C) 2012 jason m horwitz, Sekat LLC. All Rights Reserved.

NAME="semver"
DESC="Manipulate semantical version strings '<major>.<minor>.<patch>' (@see http://semver.org)."
VERSION="1.0.0"

spacer() {
	echo ""
}

usage() {
	bin="$(basename $0)"
	echo "$NAME v$VERSION - $DESC"
	echo "usage: 	$bin { -m | -n | -p } { version }"
	echo " 	$bin [ -m ] major version increment."
	echo " 	$bin [ -n ] minor version increment."
	echo " 	$bin [ -p ] patch version increment."
	echo " 	$bin [ -h --help  ] script usage."
	die
}

die() {
	echo $@
	exit 1
}

vmajor() {
	VOUT=`echo $VIN | ( IFS=".$IFS" ; read a b c && echo $((a + 1 ))."0"."0" )`
}

vminor() {
	VOUT=`echo $VIN | ( IFS=".$IFS" ; read a b c && echo $a.$((b + 1))."0" )`
}

vpatch() {
	VOUT=`echo $VIN | ( IFS=".$IFS" ; read a b c && echo $a.$b.$((c + 1)) )`
}

VIN="$BASH_ARGV"

if test -z "$BASH_ARGV"; then
	spacer
	echo "Missing Version String Argument!"
	spacer
	usage
fi

while getopts "pmnh(-help)" flag
do
	case $flag in

		h|-help)
		usage
		break;
		;;

		m)
		vmajor
		die $VOUT
		break;
		;;

		n)
		vminor
		die $VOUT
		break;
		;;

		p)
		vpatch
		die $VOUT
		;;

	esac
done

# Default to patch if version was passed without trigger
if test -z "$BASH_ARGV"; then
	exit 0
else
	vpatch
	die $VOUT
fi

exit 1