#!/bin/bash
# Bump version of python package in current directory.
# Updates version in package/__init__.py, and version embedded as
# reStructuredtext in README.
#
# Usage: BUMP package_name [new_version] [-c]
# If new_version is not specified the release part of the version will
# be incremented.
# if -c is set it will be commited and pushed.

bump_version () {
    commit=0
    while getopts "c" flag; do
        case $flag in
            c)
                commit=1
            ;;
        esac
    done
    shift $(($OPTIND - 1))
    package="$1"
    new_version="$2"
    [ $commit ] && git pull origin master
    current=$(python -c "
import $package
print($package.__version__)
    ")
    cur_major=$(echo "$current" | cut -d. -f 1)
    cur_minor=$(echo "$current" | cut -d. -f 2)
    cur_release=$(echo "$current" | cut -d. -f 3)
    if [ -z "$new_version" ]; then
        new_version="$cur_major.$cur_minor.$(($cur_release + 1))";
        new_as_tuple="($cur_major, $cur_minor, $(($cur_release + 1)))";
    fi
    new_major=$(echo "$new_version" | cut -d. -f 1)
    new_minor=$(echo "$new_version" | cut -d. -f 2)
    new_release=$(echo "$new_version" | cut -d. -f 3)

    new_as_tuple="($new_major, $new_minor, $new_release)"

    echo "$package: $current -> $new_version"

    perl -pi -e"s/(VERSION\s*=\s*)\((.+?)\);?/\$1$new_as_tuple/" \
        "$package/__init__.py"
    perl -pi -e"s/(:Version:)\s*(.+?)(\s*$)/\$1 $new_version\$3/i" README

    [ $commit ] && (
        git commit "$package/__init__.py" README \
            -m "Bumped version to $new_version";
        git push;
    )
    
}

if [ -z "$1" ]; then
    echo "Usage: $(basename $0) package_name [new_version]"
    exit 1
fi

bump_version $*