#!/bin/bash
# Exit immediately on error, treat unset variables as errors, propagate pipe failures.
set -euo pipefail
# Load shared log/warn/skip helpers from the installer library.
source "$(dirname "${BASH_SOURCE[0]}")/../../lib/logging.sh"

log "Installing MariaDB..."
# Arch ships MariaDB as the default MySQL-compatible database server.
sudo pacman -S --noconfirm --needed mariadb

# Guard against re-initialising an existing database; the mysql/ subdirectory
# is created by mariadb-install-db and its presence means the data dir is ready.
if [[ ! -d /var/lib/mysql/mysql ]]; then
    log "Initialising MariaDB data directory..."
    # mariadb-install-db creates the system tables under /var/lib/mysql,
    # running as the dedicated mysql system user for correct file ownership.
    sudo mariadb-install-db --user=mysql --basedir=/usr --datadir=/var/lib/mysql
else
    skip "MariaDB data directory already initialised."
fi

log "Enabling MariaDB service..."
# enable --now: persist across reboots and start the daemon in the current session.
enable_service mariadb.service; start_service mariadb.service
log "MariaDB installed and running."
