-
Notifications
You must be signed in to change notification settings - Fork 4
/
library.sh
77 lines (73 loc) · 2.18 KB
/
library.sh
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
#!/bin/bash
# Common entrypoint function library.
# Environment variable reading function
# The function enables reading environment variable from file.
#
# usage: file_env VAR [DEFAULT]
# ie: file_env 'XYZ_DB_PASSWORD' 'example'
# (will allow for "$XYZ_DB_PASSWORD_FILE" to fill in the value of
# "$XYZ_DB_PASSWORD" from a file, especially for Docker's secrets feature
function file_env() {
local var="$1"
local fileVar="${var}_FILE"
local def="${2:-}"
if [ "${!var:-}" ] && [ "${!fileVar:-}" ]; then
echo >&2 "error: both $var and $fileVar are set (but are exclusive)"
exit 1
fi
local val="$def"
if [ "${!var:-}" ]; then
val="${!var}"
elif [ "${!fileVar:-}" ]; then
val="$(<"${!fileVar}")"
fi
export "$var"="$val"
unset "$fileVar"
}
# Validate environment variable
# Validates the environment variable to make sure it matches expected input.
function validate_env() {
local var="$1"
local types=$(echo $2 | tr "," "\n")
for type in $types; do
local cmd=$(echo $type | cut -d= -f1)
case "$cmd" in
"req")
if [ -z "${!var}" ]; then
echo "Environment variable $var is required"
exit -1
fi
;;
"int")
if [ -n "${!var:-}" ] && [[ ${!var:-} != [0-9]* ]]; then
echo "Environment variable $var must be an integer"
exit -2
fi
;;
"dfmt")
local param=$(echo $type | cut -d= -f2)
if [ -n "${!var:-}" ] && ! date -d "${!var}" +"${param}" >/dev/null 2>&1; then
echo "Environment variable $var must be a date format ${param}"
exit -3
elif [ -n "${!var:-}" ]; then
export "$var"=$(date -d "${!var}" +"${param}")
fi
;;
"bool")
if [ -n "${!var:-}" ] && [[ ${!var:-} != "true" && ${!var:-} != "false" ]]; then
echo "Environment variable $var must be a boolean"
exit -4
fi
;;
"ip4")
ipre="^((2([0-4][0-9]|5[0-5])|[0-1]?[0-9]?[0-9])\.){3}((2([0-4][0-9]|5[0-5])|[0-1]?[0-9]?[0-9]))$"
if [ -n "${!var:-}" ] && ! [[ ${!var:-} =~ $ipre ]]; then
echo "Environment variable $var must be an IPv4 address"
exit -5
fi
esac
done
}
log () {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1"
}