#!/bin/bash
if [ $# != 2 ]; then
    echo "Usage: $0: go_cmd min_go_version" >&2
    echo "  min_go_version can be either of form x.y or x.y.z" >&2
    exit 1
fi
GOVERSION="$($1 version 2> /dev/null)"
GOVERSION="${GOVERSION//go version go/}"
GOVERSION="${GOVERSION// *}"
if [ -z "$GOVERSION" ]; then
    echo "$1 not found!"
    exit 1
fi
# GOVERSION can also be either form x.y or x.y.z
GOMAJOR="${GOVERSION/.*}"
GOMINOR="${GOVERSION#*.}"
GOPATCH="${GOMINOR#*.}"
if [ "$GOMINOR" = "$GOPATCH" ]; then
    GOPATCH=""
else
    GOMINOR="${GOMINOR/.*}"
fi
# ignore GO pre-release extensions
if ! [[ "$GOMINOR" =~ ^[0-9]$ ]]; then
    # shellcheck disable=SC2001
    GOMINOR="$(echo "$GOMINOR"|sed 's/^\([0-9]*\).*/\1/')"
fi

MINVERSION="$2"
MINMAJOR="${MINVERSION/.*}"
MINMINOR="${MINVERSION#*.}"
MINPATCH="${MINMINOR#*.}"

insufficient_go_version(){
    echo "found go $GOVERSION does not meet minimum requirement $MINVERSION!"
    exit 1
}

if [ "$MINMINOR" = "$MINPATCH" ]; then
    MINPATCH=""
else
    MINMINOR="${MINMINOR/.*}"
fi

if [ "$GOMAJOR" -lt "$MINMAJOR" ]; then
    insufficient_go_version
fi
if [ "$GOMAJOR" -gt "$MINMAJOR" ]; then
    exit 0
fi
if [ "$GOMINOR" -lt "$MINMINOR" ]; then
    insufficient_go_version
fi
if [ "$GOMINOR" -gt "$MINMINOR" ]; then
    exit 0
fi
if [ -z "$MINPATCH" ]; then
    exit 0
fi
if [ -z "$GOPATCH" ]; then
    insufficient_go_version
fi
if [ "$GOPATCH" -lt "$MINPATCH" ]; then
    insufficient_go_version
fi
exit 0
