#!/bin/bash

# Copyright (C) 2023 M.Angel Juan
#
# This file is part of LLXAMP.
#
# LLXAMP 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.
#
# LLXAMP 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 LLXAMP.  If not, see <http://www.gnu.org/licenses/>.

pass="$1"

if [ -d "@@LLXAMP_BASEPATH@@/mariadb" ]; then
    suffix=mariadb
    daemon=mariadbd
    tmpfile=$(mktemp)
    echo "ALTER USER 'root'@'localhost' IDENTIFIED BY '$pass';" > $tmpfile
    echo "FLUSH PRIVILEGES;" >> $tmpfile
else
    suffix=mysql
    daemon=mysqld
fi

export $(llxamp-status -m)
if [ "x$MYSQL_RUNNING" == "x1" ];then
    llxamp-stop-mysql
    sleep 1
    llxamp-kill-mysql
fi

if [ "$suffix" == "mysql" ];then
    @@LLXAMP_BASEPATH@@/$suffix/bin/$daemon --defaults-file=@@LLXAMP_BASEPATH@@/$suffix/conf/my.cnf --skip-grant-tables > /dev/null 2>&1 &
    while ! @@LLXAMP_BASEPATH@@/$suffix/bin/$suffix --defaults-file=@@LLXAMP_BASEPATH@@/$suffix/conf/my.cnf --user=root -e 'status' 2>/dev/null; do
        sleep 1;
    done;
    @@LLXAMP_BASEPATH@@/$suffix/bin/$suffix --defaults-file=@@LLXAMP_BASEPATH@@/$suffix/conf/my.cnf --user=root -e \"UPDATE mysql.user SET Password = PASSWORD\('\$pass'\) WHERE User = 'root';FLUSH PRIVILEGES;\"
else
    @@LLXAMP_BASEPATH@@/$suffix/bin/$daemon --defaults-file=@@LLXAMP_BASEPATH@@/$suffix/conf/my.cnf --init-file=$tmpfile > /dev/null 2>&1 &
fi
if [ -f "@@LLXAMP_BASEPATH@@/$suffix/temp/$suffix.pid" ]; then
    kill -TERM $(cat @@LLXAMP_BASEPATH@@/$suffix/temp/$suffix.pid)
fi
sleep 3
pkill -9 -f $daemon
if [ "x$MYSQL_RUNNING" == "x1" ];then
    llxamp-start-mysql
fi