forked from databacker/mysql-backup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.sh
85 lines (77 loc) · 2.3 KB
/
functions.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
78
79
80
81
82
83
84
85
#!/bin/bash
# Function definitions used in the entrypoint file.
#
# 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"
}
#
# URI parsing function
#
# The function creates global variables with the parsed results.
# It returns 0 if parsing was successful or non-zero otherwise.
#
# [schema://][user[:password]@]host[:port][/path][?[arg1=val1]...][#fragment]
#
function uri_parser() {
uri=()
# uri capture
full="$@"
# safe escaping
full="${full//\`/%60}"
full="${full//\"/%22}"
# URL that begins with '/' is like 'file:///'
if [[ "${full:0:1}" == "/" ]]; then
full="file://localhost${full}"
fi
# file:/// should be file://localhost/
if [[ "${full:0:8}" == "file:///" ]]; then
full="${full/file:\/\/\//file://localhost/}"
fi
# top level parsing
pattern='^(([a-z0-9]{2,5})://)?((([^:\/]+)(:([^@\/]*))?@)?([^:\/?]+)(:([0-9]+))?)(\/[^?]*)?(\?[^#]*)?(#.*)?$'
[[ "$full" =~ $pattern ]] || return 1;
# component extraction
full=${BASH_REMATCH[0]}
uri[uri]="$full"
uri[schema]=${BASH_REMATCH[2]}
uri[address]=${BASH_REMATCH[3]}
uri[user]=${BASH_REMATCH[5]}
uri[password]=${BASH_REMATCH[7]}
uri[host]=${BASH_REMATCH[8]}
uri[port]=${BASH_REMATCH[10]}
uri[path]=${BASH_REMATCH[11]}
uri[query]=${BASH_REMATCH[12]}
uri[fragment]=${BASH_REMATCH[13]}
if [[ ${uri[schema]} == "smb" && ${uri[path]} =~ ^/([^/]*)(/?.*)$ ]]; then
uri[share]=${BASH_REMATCH[1]}
uri[sharepath]=${BASH_REMATCH[2]}
fi
# does the user have a domain?
if [[ -n ${uri[user]} && ${uri[user]} =~ ^([^\;]+)\;(.+)$ ]]; then
uri[userdomain]=${BASH_REMATCH[1]}
uri[user]=${BASH_REMATCH[2]}
fi
return 0
}