#!/bin/bash

todo=$(CreoleGet dbCreateFixAdmin 'non')
autoRepair=$(CreoleGet dbAutoOptimizeAndRepare 'non')
role=$(CreoleGet dbClusterPosition 'Leader')

if [[ ${role} == 'Node' ]]
then
   exit 0
fi

if [[ ${todo} != 'non' ]]
then

    readerfile="/root/.mysqlreader"
    touch "${readerfile}"
    chmod 600 ${readerfile}

    tempFile=$(mktemp -p /root)
    sqlFile=$(mktemp -p /root)

    password=$(pwgen -1 10)
    /usr/share/eole/sbin/mariadbPwd ${password}

    accounts=($(CreoleGet accName))
    limits="$(CreoleGet accLimitTarget '')"
    accLimits=(${limits// /})

    previousUsers=($(awk -F ':' '{print $1}' ${readerfile} ))

    for user in ${accounts[@]}
    do
        PASS=$(awk -F ':' "/${user}:/ {print \$2}" ${readerfile})
        [[ -z ${PASS} ]] && PASS=$(openssl rand -base64 32)

        hostsList=()
        hostsList+=('localhost')
        if [[ ${accLimits[${index}]} != "Default" ]]
        then
            hostsList+=(${accLimits[${index}]//,/ })
        else
            ipAddr=($(CreoleGet ipMariaDBLimit))
            ipMask=($(CreoleGet maskMariaDBLimit))
            ix=0
            for ip in ${ipAddr[@]}
            do
                if [[ ${ipMask[${ix}]} == "255.255.255.255" ]]
                then
                    hostsList+=("${ip}")
                else
                    hostsList+=("${ip}/${ipMask[${ix}]}")
                fi
                ix=$((ix+1))
            done
        fi

        index=0
        for hst in ${hostsList[@]}
        do
            SQL="DROP USER IF EXISTS '${user}'@'${hst}';"
            SQL="${SQL} FLUSH PRIVILEGES;"
            SQL="${SQL} CREATE USER '${user}'@'${hst}' IDENTIFIED BY '${PASS}';"
            SQL="${SQL} GRANT ALL PRIVILEGES ON *.* TO '${user}'@'${hst}' WITH GRANT OPTION;"
            SQL="${SQL} FLUSH PRIVILEGES;"
            echo "${SQL}" >> ${sqlFile}
			echo "   Managing user: ${user}@${hst}"
        done
        echo "${user}:${PASS}" >> ${tempFile}

        index=$((index+1))
    done

	mysql -u root --password=${password} < ${sqlFile}

    mv ${tempFile} ${readerfile}
    chmod 600 ${readerfile}
	rm -rf ${sqlFile}
fi

if [[ ${autoRepair} == "oui" ]]
then

	mysqlcheck -u root -p ${password} --auto-repair --check --all-databases
	mysqlcheck -u root -p ${password} --optimize --check --all-databases

fi

exit 0