#!/bin/sh

. /etc/control.d/functions

CONFIG=/var/lib/mysql/my.cnf
BINARY=/usr/sbin/mysqld

[ -r $CONFIG ] || exit 1

pmysqldfirst='/^\[mysqld\]$/'
pmysqld="$pmysqldfirst,/^\[/"

checkoption()
{
	local option=$1
	sed -rn "${pmysqld}p" $CONFIG \
	| grep -Eq "^[[:space:]]*$option[[:space:]]*\$"
}

unsetoption()
{
	local option=$1
	if checkoption $option; then
		sed -ri "$pmysqld{
			s/([[:space:]]*$option[[:space:]]*)\$/#\\1/
		}" $CONFIG
	fi
}

setoption()
{
	local option=$1
	if ! checkoption $option; then
		if checkoption "#[[:space:]]*$option"; then
			sed -ri "$pmysqld{
				s/[[:space:]]*#([[:space:]]*$option[[:space:]]*)\$/\\1/
			}" $CONFIG
		else
			sed -ri "$pmysqldfirst{
				a \
$option
			}" $CONFIG
		fi
	fi
}

getstatus()
{
	local snet=
	local sgrant=

	if checkoption "skip-networking"; then
		snet="nonet"
	else
		snet="net"
	fi

	if checkoption "skip-grant-tables"; then
		sgrant="nogrant"
	else
		sgrant="grant"
	fi

	echo "$sgrant$snet"
}

register grantnet
register grantnonet
register nograntnonet
register nograntnet

new_help grantnet "For $BINARY does not use parameters skip-grant-tables and skip-networking"
new_help grantnonet "Parameter is used to $BINARY skip-networking, skip-grant-tables is not used"
new_help nograntnonet "Parameters used for $BINARY skip-grant-tables and skip-networking"
new_help nograntnet "Parameter is used to $BINARY skip-grant-tables, skip-networking is not used"

new_summary "The management of the parameters skip-grant-tables and skip-networking for mysqld"

case "$*" in
status|'')
	getstatus
	;;
grantnet)
	unsetoption "skip-grant-tables"
	unsetoption "skip-networking"
	;;
grantnonet)
	unsetoption "skip-grant-tables"
	setoption "skip-networking"
	;;
nograntnonet)
	setoption "skip-grant-tables"
	setoption "skip-networking"
	;;
nograntnet)
	setoption "skip-grant-tables"
	unsetoption "skip-networking"
	;;
*)
	control_subst "$CONFIG" "$*"
	;;
esac
