#!/usr/bin/env bash
set -euo pipefail

PACKAGE_DIR="$(cd "$(dirname "$0")/.." && pwd)"
MYSQL56_SOURCE="$PACKAGE_DIR/files/etc/my.cnf.mysql56.template"
MARIADB105_SOURCE="$PACKAGE_DIR/files/etc/my.cnf.mariadb105.template"

if [ "$(id -u)" -ne 0 ]; then
    echo "Run as root on the Sifangda database server." >&2
    exit 1
fi

if ! command -v mysql >/dev/null 2>&1; then
    echo "MySQL-compatible client not found. Install the database server first." >&2
    exit 1
fi

if mysql --version | grep -Eq 'Distrib 10\.5\.|MariaDB.*10\.5\.'; then
    DB_SOURCE="$MARIADB105_SOURCE"
    DB_LABEL="MariaDB 10.5"
elif mysql --version | grep -q '5\.6\.'; then
    DB_SOURCE="$MYSQL56_SOURCE"
    DB_LABEL="MySQL 5.6"
else
    echo "Unsupported database version: $(mysql --version)" >&2
    exit 1
fi

if grep -q '__SFD_' "$DB_SOURCE"; then
    echo "Replace __SFD_DB_SERVER_IP__ in $(basename "$DB_SOURCE") first." >&2
    exit 1
fi

mkdir -p /workspace/mysql/data /workspace/mysql/log
chown -R mysql:mysql /workspace/mysql
install -m 0644 "$DB_SOURCE" /etc/my.cnf

echo "Sifangda $DB_LABEL configuration installed."
echo "Restart MySQL, then verify bind address, character set, sql_mode and application connectivity."
