#!/usr/bin/env python
import argparse
import os
import re
import rospkg.stack
import sys

parser = argparse.ArgumentParser(description='Bump a version in your stack.xml.')
parser.add_argument('bump', choices=('major', 'minor', 'patch'), help='Which version to bump?')
args = parser.parse_args()

try:
    stack = rospkg.stack.parse_stack_file('stack.xml')
except IOError:
    print >> sys.stderr, 'This doesn\'t appear to be a catkin stack.\n\tMake sure you are in a directory with a stack.xml.'
    sys.exit(1)
except rospkg.stack.InvalidStack, e:
    print >> sys.stderr, 'Could not parse your stack.xml:\n%s' % e
    sys.exit(1)

version = re.search('(\d+)\.(\d+)\.(\d+)', stack.version).groups()
new_version = [int(x) for x in version]

# find the desired index
idx = dict(major=0, minor=1, patch=2)[args.bump]

# increment the desired version number
new_version[idx] += 1

# reset all version numbers less than this
new_version = new_version[:idx+1] + [0 for x in new_version[idx+1:]]
new_version_str = "%d.%d.%d" % tuple(new_version)

# read in the stack as string
with open('./stack.xml', 'r') as f:
    stack_str = f.read()

#write it back out
version_tag = '<version>%s</version>'
with open('./stack.xml','w') as f:
    f.write(stack_str.replace(version_tag % stack.version, version_tag % new_version_str))
