#!/bin/sh

# Generate the MySQL client credentials file used by the OpenNebula Prometheus
# MySQL exporter (mysqld_exporter --config.my-cnf=/var/lib/one/.my.cnf).
#
# The DB credentials are read from oned.conf using the OpenNebula augeas lens
# (oned.aug, shipped by the opennebula package), so no ad-hoc config parsing is
# needed.
#
# This is invoked from the package post-install scriptlet. It is intentionally
# best-effort and must never fail the install: in restricted environments where
# oned.conf, augtool or the lens are not available (for example the SUSE/OBS
# build chroot, or a host without the OpenNebula front-end) it simply does
# nothing and exits 0.

ONED_CONF="${1:-/etc/one/oned.conf}"
MYCNF="${2:-/var/lib/one/.my.cnf}"

# Nothing to do without oned.conf (build chroot, node-only host, ...).
if [ ! -f "$ONED_CONF" ]; then
    exit 0
fi

# augtool is required to parse oned.conf.
if ! command -v augtool >/dev/null 2>&1; then
    exit 0
fi

# Do not clobber an existing, possibly hand-tuned, credentials file.
if [ -e "$MYCNF" ]; then
    exit 0
fi

# Read a single key from the DB section using the OpenNebula oned lens.
# augtool prints "<path> = <value>" on success and "<path> (none)" otherwise;
# the lens keeps the surrounding quotes, e.g.  .../DB/USER = "oneadmin".
aug_get() {
    _out=$(augtool -A 2>/dev/null <<AUGEOF || :
set /augeas/load/Oned/lens Oned.lns
set /augeas/load/Oned/incl $ONED_CONF
load
get /files$ONED_CONF/DB/$1
AUGEOF
)
    case "$_out" in
        *' = '*) ;;
        *) return 0 ;;
    esac
    _val=${_out#* = }
    case "$_val" in
        \"*\") _val=${_val#\"}; _val=${_val%\"} ;;
    esac
    printf '%s' "$_val"
}

# Only mysql/mariadb back-ends use a my.cnf credentials file.
backend=$(aug_get BACKEND)
if [ "$backend" != "mysql" ]; then
    exit 0
fi

db_user=$(aug_get USER)
db_pass=$(aug_get PASSWD)

# Without a user there is nothing useful to write.
if [ -z "$db_user" ]; then
    exit 0
fi

umask 077
mkdir -p "$(dirname "$MYCNF")"
cat <<MYCNFEOF > "$MYCNF"
[client]
user = $db_user
password = $db_pass
MYCNFEOF

# The exporter runs as oneadmin and must be able to read the file.
if getent passwd oneadmin >/dev/null 2>&1; then
    chown oneadmin:oneadmin "$MYCNF" 2>/dev/null || :
fi
chmod 600 "$MYCNF" 2>/dev/null || :

exit 0
