#!/usr/bin/env python
import yaml, os, sys, argparse, re

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

if os.path.exists('./stack.yaml'):
  stack_yaml = yaml.load(open('./stack.yaml'))
else:
  print >>sys.stderr, 'This doesn\'t appear to be a catkin stack.\n\tMake sure you are in a directory with a stack.yaml.'
  sys.exit(1)

version = re.search('(\d+)\.(\d+)\.(\d+)',stack_yaml['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:]]
version_str = "%d.%d.%d"%tuple(new_version)

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

#write it back out...
with open('./stack.yaml','w') as f:
  f.write(re.sub(r'Version\:\s*(\d+\.\d+\.\d+)','Version: %s'%version_str,stack_str))
