#!/bin/bash

# https://stackoverflow.com/a/4025065

# does not handle mixed digit/nondigit fields e.g. "2a" well, just compares
# them asciibetically. rpm, for example, would split those into multiple
# fields like (2 a). doing that properly would complicate the code too much.

if [[ $1 == $2 ]]
then
    exit 0
fi
IFS=.
ver1=($1)
ver2=($2)
# fill empty fields in ver1 with zeros
for ((i=${#ver1[@]}; i<${#ver2[@]}; i++))
do
    ver1[i]=0
done
for ((i=0; i<${#ver1[@]}; i++))
do
    if [[ -z ${ver2[i]} ]]
    then
        # fill empty fields in ver2 with zeros
        ver2[i]=0
    fi
    if [[ ${ver1[i]} =~ ^[0-9]+$ && ${ver2[i]} =~ ^[0-9]+$ ]]
    then
        # all numeric characters -- do integer comparison
        # the "10#" forces the numbers to be considered decimal, even in the
        # presence of leading zeroes.
        if ((10#${ver1[i]} > 10#${ver2[i]}))
        then
            exit 1
        fi
        if ((10#${ver1[i]} < 10#${ver2[i]}))
        then
            exit 2
        fi
    else
        # non-numeric characters found -- do ascii comparison
        if [[ ${ver1[i]} > ${ver2[i]} ]]
        then
            exit 1
        fi
        if [[ ${ver1[i]} < ${ver2[i]} ]]
        then
            exit 2
        fi
    fi
done

exit 0
