Files
imagefind/scripts/docker-entrypoint.sh

59 lines
2.4 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
PG_BIN=/usr/lib/postgresql/15/bin
PG_DATA=/data/postgresql
PG_LOG="$PG_DATA/postgresql.log"
APP_DATA=/data/imagefind
PG_CONF=/data/postgres-client.conf
ADMIN_MARKER=/data/.imagefind-admin-initialized
mkdir -p "$PG_DATA" "$APP_DATA" /data/runtime
chown -R postgres:postgres "$PG_DATA"
chown -R imagefind:imagefind "$APP_DATA" /data/runtime
if [ ! -s "$PG_DATA/PG_VERSION" ]; then
runuser -u postgres -- "$PG_BIN/initdb" -D "$PG_DATA" --auth-local=trust --auth-host=scram-sha-256
printf '%s\n' "listen_addresses = '127.0.0.1'" "port = 5432" >>"$PG_DATA/postgresql.conf"
fi
runuser -u postgres -- "$PG_BIN/pg_ctl" -D "$PG_DATA" -l "$PG_LOG" -w start
stop_postgres() {
runuser -u postgres -- "$PG_BIN/pg_ctl" -D "$PG_DATA" -m fast -w stop >/dev/null 2>&1 || true
}
trap stop_postgres EXIT TERM INT HUP
if [ ! -s "$PG_CONF" ]; then
role_exists=$(runuser -u postgres -- psql -Atqc "SELECT 1 FROM pg_roles WHERE rolname='imagefind'" postgres)
db_exists=$(runuser -u postgres -- psql -Atqc "SELECT 1 FROM pg_database WHERE datname='imagefind'" postgres)
if [ -n "$role_exists" ] || [ -n "$db_exists" ]; then
printf 'PostgreSQL data exists but %s is missing; refusing to replace credentials.\n' "$PG_CONF" >&2
exit 1
fi
db_password=$(python -c 'import secrets; print(secrets.token_urlsafe(48))')
runuser -u postgres -- psql -v ON_ERROR_STOP=1 -v password="$db_password" postgres <<'SQL'
CREATE ROLE imagefind LOGIN PASSWORD :'password';
SQL
runuser -u postgres -- createdb --owner=imagefind imagefind
runuser -u postgres -- psql -v ON_ERROR_STOP=1 imagefind -c 'CREATE EXTENSION IF NOT EXISTS vector; CREATE EXTENSION IF NOT EXISTS pg_trgm;'
umask 077
printf 'host=127.0.0.1\nport=5432\ndatabase=imagefind\nusername=imagefind\npassword=%s\nsslmode=Disable\n' \
"$db_password" >"$PG_CONF"
chown imagefind:imagefind "$PG_CONF"
fi
if [ ! -e "$ADMIN_MARKER" ]; then
: "${IMAGEFIND_ADMIN_PASSWORD:?IMAGEFIND_ADMIN_PASSWORD is required for first initialization}"
printf '%s' "$IMAGEFIND_ADMIN_PASSWORD" | runuser -u imagefind --preserve-environment -- imagefind admin-password --stdin
install -o imagefind -g imagefind -m 0600 /dev/null "$ADMIN_MARKER"
fi
unset IMAGEFIND_ADMIN_PASSWORD || true
runuser -u imagefind --preserve-environment -- imagefind &
app_pid=$!
set +e
wait "$app_pid"
status=$?
set -e
exit "$status"