11#! /bin/bash
22set -e
33
4+ # usage: file_env VAR [DEFAULT]
5+ # ie: file_env 'XYZ_DB_PASSWORD' 'example'
6+ # (will allow for "$XYZ_DB_PASSWORD_FILE" to fill in the value of
7+ # "$XYZ_DB_PASSWORD" from a file, especially for Docker's secrets feature)
8+ file_env () {
9+ local var=" $1 "
10+ local fileVar=" ${var} _FILE"
11+ local def=" ${2:- } "
12+ if [ " ${! var:- } " ] && [ " ${! fileVar:- } " ]; then
13+ echo >&2 " error: both $var and $fileVar are set (but are exclusive)"
14+ exit 1
15+ fi
16+ local val=" $def "
17+ if [ " ${! var:- } " ]; then
18+ val=" ${! var} "
19+ elif [ " ${! fileVar:- } " ]; then
20+ val=" $( < " ${! fileVar} " ) "
21+ fi
22+ export " $var " =" $val "
23+ unset " $fileVar "
24+ }
25+
426if [ " ${1: 0: 1} " = ' -' ]; then
527 set -- postgres " $@ "
628fi
@@ -16,10 +38,12 @@ if [ "$1" = 'postgres' ]; then
1638
1739 # look specifically for PG_VERSION, as it is expected in the DB dir
1840 if [ ! -s " $PGDATA /PG_VERSION" ]; then
41+ file_env ' POSTGRES_INITDB_ARGS'
1942 eval " su-exec postgres initdb $POSTGRES_INITDB_ARGS "
2043
2144 # check password first so we can output the warning before postgres
2245 # messes it up
46+ file_env ' POSTGRES_PASSWORD'
2347 if [ " $POSTGRES_PASSWORD " ]; then
2448 pass=" PASSWORD '$POSTGRES_PASSWORD '"
2549 authMethod=md5
@@ -51,9 +75,8 @@ if [ "$1" = 'postgres' ]; then
5175 -o " -c listen_addresses='localhost'" \
5276 -w start
5377
54- : ${POSTGRES_USER:= postgres}
55- : ${POSTGRES_DB:= $POSTGRES_USER }
56- export POSTGRES_USER POSTGRES_DB
78+ file_env ' POSTGRES_USER' ' postgres'
79+ file_env ' POSTGRES_DB' " $POSTGRES_USER "
5780
5881 psql=( psql -v ON_ERROR_STOP=1 )
5982
0 commit comments