#!/bin/sh -e
#
# 2020 Ander Punnar (ander-at-kvlt-dot-ee)
#
# This file is part of cdist.
#
# cdist is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cdist is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cdist. If not, see <http://www.gnu.org/licenses/>.
#

state_is="$( cat "$__object/explorer/state" )"

state_should="$( cat "$__object/parameter/state" )"

if [ "$state_is" = "$state_should" ]
then
    exit 0
fi

if [ -f "$__object/parameter/name" ]
then
    name="$( cat "$__object/parameter/name" )"
else
    name="$__object_id"
fi

host="$( cat "$__object/parameter/host" )"

if [ -f "$__object/parameter/password" ]
then
    password="$( cat "$__object/parameter/password" )"
else
    if [ "$state_should" = 'present' ]
    then
        echo '--password needed' >&2
        exit 1
    else
        password=''
    fi
fi

if [ "$state_is" = 'absent' ] && [ "$state_should" = 'present' ]
then
    echo "mysql -e 'create user \`$name\`@\`$host\` identified by \"$password\"'"
    echo "create user $name@$host" >> "$__messages_out"

elif [ "$state_is" != 'absent' ] && [ "$state_should" = 'absent' ]
then
    echo "mysql -e 'drop user \`$name\`@\`$host\`'"
    echo "drop user $name@$host" >> "$__messages_out"

elif [ "$state_is" = 'change-password' ]
then
    # this only works with MySQL 5.7.6 and later or MariaDB 10.1.20 and later
    echo "mysql -e 'alter user \`$name\`@\`$host\` identified by \"$password\"'"
    echo "mysql -e 'flush privileges'"
    echo "change password $name@$host" >> "$__messages_out"
fi
