#!/bin/bash
#
# Copyright (C) 2023 MOXA Inc. All rights reserved.
# This software is distributed under the terms of the MOXA SOFTWARE NOTICE.
# See the file LICENSE for details.
#
# Authors:
#       2023  Wilson YS Huang  <wilsonys.huang@moxa.com>

ver::get_major() {
        local version
        version="$1"

        echo "$version" | awk -F '.' '{print $1}'
}

ver::get_minor() {
        local version
        version="$1"

        echo "$version" | awk -F '.' '{print $2}'
}

ascii() {
        printf "%d" "'$1"
}

isdigit() {
        local c
        c="$1"
        [[ "$c" =~ [[:digit:]] ]]
}

# Return 0 if v1 and v2 are equal
# Return <0 if v1 is smaller then v2
# Return >0 if v1 is greater then v2
ver::compare() {
        local v1
        local v2
        local c1
        local c2
        local v1_idx
        local v2_idx
        local diff

        v1="$1"
        v2="$2"
        v1_idx=0
        v2_idx=0

        if [[ "$v1" == "$v2" ]]; then
                echo 0
                return
        fi

        while [[ -n "${v1:$v1_idx:1}" ]] || [[ -n "${v2:$v2_idx:1}" ]]; do
                diff=0

                # Handle non digit
                while [[ -n "${v1:$v1_idx:1}" ]] && ! isdigit "${v1:$v1_idx:1}" ||
                        [[ -n "${v2:$v2_idx:1}" ]] && ! isdigit "${v2:$v2_idx:1}"; do

                        c1=$(ascii "${v1:$v1_idx:1}")
                        c2=$(ascii "${v2:$v2_idx:1}")

                        if [[ $diff -eq 0 ]]; then
                                diff=$((c1 - c2))
                        fi

                        ((v1_idx++))
                        ((v2_idx++))
                done

                # Handle digit
                while isdigit "${v1:$v1_idx:1}" && isdigit "${v2:$v2_idx:1}"; do
                        if [[ $diff -eq 0 ]]; then
                                diff=$((${v1:$v1_idx:1} - ${v2:$v2_idx:1}))
                        fi

                        ((v1_idx++))
                        ((v2_idx++))
                done

                # Handle length v1 > v2 if substring prefix is the same
                if isdigit "${v1:$v1_idx:1}"; then
                        echo 1
                        return
                fi

                # Handle length v1 < v2 if substring prefix is the same
                if isdigit "${v2:$v2_idx:1}"; then
                        echo -1
                        return
                fi

                if [[ $diff -ne 0 ]]; then
                        echo $diff
                        return
                fi
        done

        echo 0
}
