summaryrefslogtreecommitdiff
path: root/chkver
blob: 6e3f9217a393acd7831fb3ec9ff648d7ca82362f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#! /bin/bash
#
# Copyright 2016 Software Freedom Conservancy Inc.
#
# This software is licensed under the GNU LGPL (version 2.1 or later).
# See the COPYING file in this distribution.
#
# chkver <min | max> <major.minor.revision> <min|max major.minor.revision>
#
# Returns 0 if queried version is greater than or equal (for min) or lesser than (for max) the
# supplied value, or 1 otherwise.
#
# Set VERBOSE environment variable for somewhat useful output.
#
# NOTE:
# This is an ultra-naive implementation with just enough error-checking.

usage() {
    echo 'usage: chkver <min | max> <major.minor.revision> <min|max major.minor.revision>'
}

abort() {
    usage
    exit 1
}

verify_cardinal() {
    while [ $# != 0 ]
    do
        if [ $1 ] && [ $1 -eq $1 2> /dev/null ] && [ $1 -ge 0 ]
        then
            :
        else
            abort
        fi
        
        shift
    done
}

# check_min name number min-number
check_min() {
    if [ $2 -gt $3 ]
    then
        verbose $1 large enough.
        exit 0
    elif [ $2 -lt $3 ]
    then
        verbose $1 not large enough.
        exit 1
    fi
}

# check_max name number max-number
check_max() {
    if [ $2 -lt $3 ]
    then
        verbose $1 small enough.
        exit 0
    elif [ $2 -gt $3 ]
    then
        verbose $1 not small enough.
        exit 1
    fi
}

verbose() {
    if [ $VERBOSE ]
    then
        echo $*
    fi
}

# Check number of arguments
if [ $# -lt 3 ]
then
    abort
fi

# Parse arguments
mode=$1
if [ $mode != "min" ] && [ $mode != "max" ]
then
    abort
fi

major=`echo $2 | awk -F. '{print $1}'`
minor=`echo $2 | awk -F. '{print $2}'`
revision=`echo $2 | awk -F. '{print $3}'`

min_major=`echo $3 | awk -F. '{print $1}'`
min_minor=`echo $3 | awk -F. '{print $2}'`
min_revision=`echo $3 | awk -F. '{print $3}'`

# Verify they're all positive integers
verify_cardinal "$major" "$minor" "$revision" "$min_major" "$min_minor" "$min_revision"

verbose Comparing $major.$minor.$revision against $mode $min_major.$min_minor.$min_revision

# check version numbers in order of importance
if [ $mode == "min" ]
then
    check_min "Major" $major $min_major
    check_min "Minor" $minor $min_minor
    check_min "Revision" $revision $min_revision
else
    check_max "Major" $major $min_major
    check_max "Minor" $minor $min_minor
    check_max "Revision" $revision $min_revision
fi

verbose Same version.
if [ $mode == "min" ]
then
    exit 0
else
    exit 1
fi