#!/bin/bash

# Path to the grastate.dat file
GRSTATE_FILE="/var/lib/mysql/grastate.dat"

# Check if the MARIADB_SLAVE environment variable is set
if [ ! -z "$MARIADB_SLAVE" ]; then
    # If MARIADB_SLAVE is set, this node is a slave, so just run mariadbd (no --wsrep-new-cluster)
    echo "MARIADB_SLAVE environment variable is set. Starting as a slave node."
    exec mariadbd "$@"
else
    # If grastate.dat exists, check if the cluster has already been bootstrapped
    if [ -f "$GRSTATE_FILE" ]; then
        # Read the value of safe_to_bootstrap from grastate.dat
        SAFE_TO_BOOTSTRAP=$(grep -E "^safe_to_bootstrap" "$GRSTATE_FILE" | cut -d ':' -f 2 | tr -d ' ')

        if [ "$SAFE_TO_BOOTSTRAP" == "1" ]; then
            # Cluster is already bootstrapped, so start mariadbd without --wsrep-new-cluster
            echo "Cluster is already bootstrapped. Starting mariadbd without --wsrep-new-cluster."
            exec mariadbd "$@"
        else
            # Cluster is not bootstrapped, so run mariadbd with --wsrep-new-cluster
            echo "Cluster is not bootstrapped. Bootstrapping the cluster."
            exec mariadbd --wsrep-new-cluster "$@"
        fi
    else
        # If grastate.dat doesn't exist, assume it's a new cluster and bootstrap it
        echo "grastate.dat not found. Bootstrapping the cluster."
        exec mariadbd --wsrep-new-cluster "$@"
    fi
fi
