#!/usr/bin/env ruby
#
# bump_version
#

###
### dependencies
###

require 'open3'
require 'rubygems'

###
### configurable constants
###

VERSION_FILE          = 'lib/hbc/version.rb'
VERSION_PAT           = %r[\d+\.\d+\.\d+]i
VERSION_CONSTANT_NAME = 'HBC_VERSION'

###
### methods
###

def cd_to_project_root
  Dir.chdir File.dirname(File.expand_path(__FILE__))
  @git_root ||= Open3.popen3(*%w[
                                 git rev-parse --show-toplevel
                                ]) do |stdin, stdout, stderr|
    begin
      stdout.gets.chomp
    rescue
    end
  end
  Dir.chdir @git_root
  @git_root
end

def git_diff
  Open3.popen3(*%w[
                   git diff --no-color --
                  ],
               VERSION_FILE) do |stdin, stdout, stderr|
    stdout.each_line.map(&:chomp)
  end
end

def file_contents_pat
  %r{\A(#{VERSION_CONSTANT_NAME}\s+=\s+)'(#{VERSION_PAT})'\s*\Z}s
end

def current_file_contents
  @current_file_contents ||= File.read(VERSION_FILE)
end

def current_file_version
  if file_contents_pat.match(current_file_contents)
    $2
  else
    raise "Could not parse file '#{VERSION_FILE}'"
  end
end

def sanity_check
  unless %r{\A#{VERSION_PAT}\Z}.match(proposed_version)
    raise "Proposed version '#{proposed_version}' does not look like a semantic version string"
  end
  unless %r{\A#{VERSION_PAT}\Z}.match(current_file_version)
    raise "Current version '#{current_file_version}' does not look like a semantic version string"
  end
  unless Gem::Version.new(proposed_version) > Gem::Version.new(current_file_version)
    raise "Proposed version '#{proposed_version}' is not greater than current version #{current_file_version}"
  end
end

def usage
  <<EOT
bump_version <new-version>

Bump the version number in #{VERSION_FILE} to match the
number given on the command line.

EOT
end

def proposed_version
  @proposed_version ||= ARGV.first.sub(/^v/i, '')
end

def rewrite_version
  new_file_contents = current_file_contents
  if new_file_contents.sub!(file_contents_pat, "\\1'#{proposed_version}'\n")
    File.open(VERSION_FILE, 'w') {|f| f.write(new_file_contents) }
  else
    raise "Could not parse file '#{VERSION_FILE}'"
  end
end

###
### main
###

# process args
if %r{\A-+h(?:elp)?}i.match(ARGV.first)
  puts usage
  exit
elsif ARGV.length != 1 or ! %r{\Av?#{VERSION_PAT}\Z}.match(ARGV.first)
  puts usage
  exit 1
end

# initialize
cd_to_project_root

# dispatch
sanity_check
rewrite_version
puts git_diff
