#!/usr/bin/env bash # Container entrypoint (docs/DEPLOY.md ยง2.4, ADR 0013, ADR 0014). It only prepares the user, waits for the system # database and starts the app: migrations and bootstrap live in the .NET code. set -euo pipefail APP_DLL=/app/Khaemhat.Web.dll DATA_DIR="${KHAEMHAT_DATA_DIR:-/data}" DB_WAIT_SECONDS=120 log() { printf '%s khaemhat-entrypoint: %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" >&2; } fail() { log "ERRORE: $*"; exit 1; } # The system database URL, from KHAEMHAT_SYSTEM_DB or KHAEMHAT_SYSTEM_DB_FILE (ADR 0014). Only host and port are used. system_db() { if [[ -n "${KHAEMHAT_SYSTEM_DB:-}" && -n "${KHAEMHAT_SYSTEM_DB_FILE:-}" ]]; then fail "KHAEMHAT_SYSTEM_DB e KHAEMHAT_SYSTEM_DB_FILE sono entrambe impostate: usane una sola." fi if [[ -n "${KHAEMHAT_SYSTEM_DB_FILE:-}" ]]; then [[ -r "$KHAEMHAT_SYSTEM_DB_FILE" ]] || fail "KHAEMHAT_SYSTEM_DB_FILE: file non leggibile ($KHAEMHAT_SYSTEM_DB_FILE)." head -n 1 "$KHAEMHAT_SYSTEM_DB_FILE" | tr -d '\r\n' else printf '%s' "${KHAEMHAT_SYSTEM_DB:-}" fi } # Waits until the PostgreSQL server of the system database accepts connections. SQLite needs no wait. wait_for_database() { local url host port rest deadline url="$(system_db)" case "$url" in postgres://* | postgresql://*) ;; *) return 0 ;; esac rest="${url#*://}" # user:pwd@host:port/db?x rest="${rest##*@}" # host:port/db?x rest="${rest%%/*}" # host:port rest="${rest%%\?*}" host="${rest%%:*}" port=5432 [[ "$rest" == *:* ]] && port="${rest##*:}" [[ -n "$host" ]] || fail "KHAEMHAT_SYSTEM_DB: host mancante." deadline=$((SECONDS + DB_WAIT_SECONDS)) until pg_isready -q -h "$host" -p "$port" -t 3; do if (( SECONDS >= deadline )); then fail "il database di sistema su $host:$port non risponde dopo ${DB_WAIT_SECONDS}s." fi log "attendo il database di sistema su $host:$port..." sleep 2 done log "database di sistema raggiungibile su $host:$port." } # Aligns the "app" user with PUID/PGID and gives it /data (ADR 0013). Only when started as root. prepare_user() { local puid="${PUID:-$(id -u app)}" pgid="${PGID:-$(id -g app)}" [[ "$puid" =~ ^[0-9]+$ && "$pgid" =~ ^[0-9]+$ ]] || fail "PUID e PGID devono essere numeri (PUID=$puid, PGID=$pgid)." (( puid != 0 && pgid != 0 )) || fail "PUID e PGID non possono essere 0: l'applicazione non gira come root." if [[ "$(id -g app)" != "$pgid" ]]; then groupmod -o -g "$pgid" app fi if [[ "$(id -u app)" != "$puid" ]]; then usermod -o -u "$puid" app fi mkdir -p "$DATA_DIR" if [[ "$(stat -c '%u:%g' "$DATA_DIR")" != "$puid:$pgid" ]]; then log "assegno $DATA_DIR a $puid:$pgid..." chown -R "$puid:$pgid" "$DATA_DIR" fi } wait_for_database if [[ "$(id -u)" == "0" ]]; then prepare_user log "avvio Khaemhat come utente app ($(id -u app):$(id -g app))." exec setpriv --reuid=app --regid=app --init-groups -- dotnet "$APP_DLL" "$@" fi log "avvio Khaemhat come utente $(id -u):$(id -g)." exec dotnet "$APP_DLL" "$@"