#!/bin/bash
# Runs once before MariaDB starts (compose service "secrets"): generates the database root password into the secrets volume.
# Owned by uid 999 (the mysql user of the MariaDB image) and readable by nobody else; root in the Saan container reads it too.
set -euo pipefail
SEC=/srv/saan-secrets
mkdir -p "$SEC"; chmod 0711 "$SEC"
if [ ! -s "$SEC/db-root-password" ]; then
    umask 077
    openssl rand -base64 96 | LC_ALL=C tr -dc 'A-Za-z0-9' | cut -c1-32 | tr -d '\n' > "$SEC/db-root-password"   # cut reads everything: no SIGPIPE under pipefail
    echo "[saan] [OK] database root password generated"
else
    echo "[saan] [OK] database root password already there"
fi
chown 999:999 "$SEC/db-root-password"; chmod 0400 "$SEC/db-root-password"
