#!/bin/sh

[ -n "$PLESK_INSTALLER_DEBUG" ] && set -x

echo -n "Commenting out 'skip-bdb' option in my.cnf... "

need_check()
{
    top_version=50
    version=0

    if which rpm >/dev/null 2>&1; then
        if rpm -qi mysql-server 1>/dev/null 2>&1; then
            version="`rpm -q --qf '%{VERSION}' mysql-server | awk -F '.' '{print $1$2}'`"
        fi
        if rpm -qi mariadb 1>/dev/null 2>&1; then
            version="`rpm -q --qf '%{VERSION}' mariadb | awk -F '.' '{print $1$2}'`"
        fi
    fi

    if which dpkg >/dev/null 2>&1; then
        installed="`dpkg --get-selections mysql-common 2>/dev/null | awk '{if ($2 == \"install\") {print $1}}'`"
        if [ -n "$installed" ]; then
            version="`dpkg-query -W -f='${Version}' mysql-common | awk -F '.' '{print $1$2}'`"
        fi
    fi

    [ "$version" -gt "$top_version" ] && return 0

    echo "is not required"

    return 1
}

find_my_cnf()
{
    local non_fatal="$1"
    local cnf_files="/etc/my.cnf /etc/mysql/my.cnf /var/db/mysql/my.cnf"

    for my_cnf in $cnf_files; do
        [ -f "$my_cnf" ] && return 0
    done

    return 1
}

fix_config()
{
    need_fix="`cat $my_cnf | grep 'skip-bdb' | grep -v '#skip-bdb'`"
    [ -z "$need_fix" ] && return 1

    awk '/^[[:space:]]*skip-bdb[[:space:]]*(#.*)?$/ {print "#"$0; next;}{print;}' < $my_cnf > ${my_cnf}.mu
    mv -f ${my_cnf}.mu $my_cnf
    return 0
}

need_check || exit 0

find_my_cnf && fix_config && echo "done" || echo "is not required"

exit 0
