#!/bin/bash
#
# Compare version strings of the typical format used at NI, for example
# 1.2.3f4 -- major, minor, subminor, phase (dev, alpha, beta, release
# candidate, final) and build.
#
# Subminor, phase, and build are optional.
#
# Returns "equal", "newer" (if $2 is newer than $1), or "older" (if $2 is
# older than $1).

if [ $# -ne 2 ]; then
	echo "Usage: `basename $0` <version 1> <version 2>"
	exit 1
fi

version_regex='([0-9]+)\.([0-9]+)(\.([0-9]+)((d|a|b|rc|f)([0-9]+))?)?'
maj_match_num=0
min_match_num=1
# match 2 is subminor, phase, and build (which are optional)
submin_match_num=3
# match 4 is phase and build (which are optional)
phase_match_num=5
build_match_num=6

# extract array of version data from the strings
declare -a ver1 ver2
[[ $1 =~ $version_regex ]]
ver1=(${BASH_REMATCH[@]:1})
[[ $2 =~ $version_regex ]]
ver2=(${BASH_REMATCH[@]:1})

# map phase (dev, alpha, beta, RC, final) to integer, default to final
# so that if we just have a version like 3.0.0 we assume it's final
readonly -A phase_map=([d]=0 [a]=1 [b]=2 [rc]=3 [f]=4)
ver1[$phase_match_num]=${phase_map[${ver1[$phase_match_num]:-f}]}
ver2[$phase_match_num]=${phase_map[${ver2[$phase_match_num]:-f}]}

# for each element of the array (major, minor, patch, phase, build)
# check if ver1 and ver2 are equal, if so, continue, else return,
# printing the result of the compare
for i in $maj_match_num $min_match_num $submin_match_num $phase_match_num $build_match_num
	do
		case $(( ${ver1[$i]:-0} - ${ver2[$i]:-0} )) in
			0) ;;
			-*) echo newer && exit 0 ;;
			*) echo older && exit 0 ;;
		esac
	done

echo equal


