9b8127d2ee2c2dc37d81381753d781baf399582b
[gsu.git] / misc / gsu / common
1 #!/bin/bash
2 # (C) 2006-2011 Andre Noll
3
4 _gsu_init_errors()
5 {
6 gsu_errors="
7 GSU_SUCCESS success
8 E_GSU_BAD_COMMAND invalid command
9 E_GSU_NOT_A_NUMBER not a number
10 E_GSU_BAD_CONFIG_VAR invalid config variable
11 E_GSU_NEED_VALUE value required but not given
12 E_GSU_BAD_BOOL bad value for boolian option
13 E_GSU_BAD_OPTION_TYPE invalid option type
14 E_GSU_BAD_ARG_COUNT invalid number of arguments
15 E_GSU_EDITOR failed to execute editor
16 E_GSU_MKDIR failed to create directory
17 E_GSU_GETOPTS getopts error
18 $gsu_errors
19 "
20 local a b i=0
21 while read a b; do
22 if test -z "$a"; then
23 continue
24 fi
25 #echo "a:$a, b: $b"
26 gsu_error_txt[i]="$b"
27 eval $a=$i
28 i=$(($i + 1))
29 done << EOF
30 $gsu_errors
31 EOF
32 }
33
34 # check if $1 is a number
35 gsu_is_a_number()
36 {
37 result="$1"
38 if test "$1" -eq "$1" &> /dev/null; then
39 ret=$GSU_SUCCESS
40 else
41 ret=-$E_GSU_NOT_A_NUMBER
42 fi
43 }
44
45 gsu_short_msg()
46 {
47 echo "$1" 1>&2
48 }
49
50 gsu_msg()
51 {
52 gsu_short_msg "$_gsu_self: $1"
53 }
54
55 gsu_date_msg()
56 {
57 gsu_short_msg "$_gsu_self $(date): $1"
58 }
59
60 gsu_err_msg()
61 {
62 local txt="$result" err
63
64 gsu_is_a_number "$ret"
65 if test $ret -lt 0; then
66 gsu_msg "unknown error ($ret:$txt)"
67 exit 1
68 fi
69 if test $result -ge 0; then
70 gsu_msg "unknown error ($result:$txt)"
71 exit 1
72 fi
73 err=$((0 - $result))
74 if test -n "$txt"; then
75 txt="$txt: ${gsu_error_txt[$err]}"
76 else
77 txt="${gsu_error_txt[$err]}"
78 fi
79 gsu_msg "$txt"
80 }
81
82 _gsu_setup()
83 {
84 _gsu_self="$(basename $0)"
85 gsu_name="${gsu_name:=$_gsu_self}"
86 gsu_config_var_prefix="${gsu_config_var_prefix:=$gsu_name}"
87 _gsu_init_errors
88 }