-
Notifications
You must be signed in to change notification settings - Fork 1
/
entrypoint.sh
executable file
·82 lines (60 loc) · 1.88 KB
/
entrypoint.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
#!/usr/bin/env bash
set -euo pipefail
export DL_ENV="${DL_ENV:-dev}"
log() {
echo "$(date +"%H:%M:%S") - $(printf '%s' "$@")" 1>&2
}
error() {
local message="${1}"
echo "$(date +"%H:%M:%S") - ERROR: $(printf '%s' "${message}")" >&2
exit 55
}
wait_for_postgres() {
local dburi="${1}"
log "wait for postgres ${dburi}"
until psql "${dburi}" -c '\q' 2> /dev/null; do
sleep 1
log "postgres not ready"
done
}
ensure_db() {
local dburi="${1}"
local dbname="${2}"
if [[ "$(psql "${dburi}" -tAc "SELECT 1 FROM pg_database WHERE datname = '${dbname}'")" != "1" ]]; then
log "create DB ${dbname}"
psql "${dburi}" -c "CREATE DATABASE ${dbname};" > /dev/null
fi
}
write_reset_script() {
local appdb="${1}"
local file="${HOME}/reset-db.sh"
log "writing ${file}"
cat <<EOF > "${file}"
#!/usr/bin/env bash
migrate -path "${HOME}/migrations" -database "${appdb}?sslmode=disable" down -all
migrate -path "${HOME}/migrations" -database "${appdb}?sslmode=disable" up
EOF
chmod +x "${file}"
}
main() {
if [[ "$#" -ne 3 ]]; then
error "Usage: ${0} <port> <dburi> <dbname>"
fi
local port="${1}"
local dburi="${2}"
local dbname="${3}"
local rootdb="${dburi}/postgres"
local appdb="${dburi}/${dbname}"
wait_for_postgres "${rootdb}"
ensure_db "${rootdb}" "${dbname}"
write_reset_script "${appdb}"
if [[ "${RUN_MIGRATIONS:-0}" == "1" ]]; then
log "run migrations"
migrate -path "${HOME}/migrations" -database "${appdb}?sslmode=disable" up
fi
local log_level="${DL_LOG_LEVEL:-info}"
local secrets="${HOME}/secrets"
log "start dateilager server"
"${HOME}/server" --dburi "${appdb}" --port "${port}" --log-level "${log_level}" --cert "${secrets}/tls/server.crt" --key "${secrets}/tls/server.key" --paseto "${secrets}/paseto/paseto.pub"
}
main "$@"