#!/bin/bash

SLE_VERSION_REGEX="([0-9]{6}\.|slfo[\.0-9]+_|)"
VERSION_REGEX="($SLE_VERSION_REGEX[0-9\.]+[0-9])+"

VERSION_1=$(echo "$1" | grep -Eo $VERSION_REGEX | tail -1)
VERSION_2=$(echo "$2" | grep -Eo $VERSION_REGEX | tail -1)

SLE_VERSION_1=$(echo "$VERSION_1" | grep -Eo $SLE_VERSION_REGEX)
SLE_VERSION_2=$(echo "$VERSION_2" | grep -Eo $SLE_VERSION_REGEX)

# Check if we are comparing the same SLE versions.
if [ "$SLE_VERSION_1" != "$SLE_VERSION_2" ]; then
  exit 2 # We can't compare those.
fi

# Remove the SLE version prefix from the version string.
SUFFIX_V1="${VERSION_1#$SLE_VERSION_1}"
SUFFIX_V2="${VERSION_2#$SLE_VERSION_2}"

# Tokenize
ARR_V1=(${SUFFIX_V1//./ })
ARR_V2=(${SUFFIX_V2//./ })

# Get length
LEN_1=${#ARR_V1[@]}
LEN_2=${#ARR_V2[@]}

# Get minimum.
if [[ $LEN_1 -le $LEN_2 ]]; then
  LEN=$LEN_1
else
  LEN=$LEN_2
fi

for i in $(seq 0 $(($LEN-1))); do
  V1=${ARR_V1[$i]}
  V2=${ARR_V2[$i]}

  if [[ $V1 -lt $V2 ]]; then
    exit 0
  elif [[ $V1 -gt $V2 ]]; then
    exit 1
  fi
done

exit 1
