#!/bin/bash

# Copyright: 2023 Virtuozzo International GmbH

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

# http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

[ -n "${MYSQLPASSWDLIB_VERSION:-}" ] && return 0;
MYSQLPASSWDLIB_VERSION="0.1";

include log;
include output;

LOG_FILE=/var/log/msqlresetpas.log;
$PROGRAM 'mysqld_safe';
$PROGRAM 'mysql';
$PROGRAM 'chkconfig';
$PROGRAM 'grep';
$PROGRAM 'mysqladmin';

function setPassword() {

		/usr/bin/chown -R mysql:mysql /var/log/mysql &>/dev/null;

		while [ "$1" != "" ];
		do
		  case $1 in
		    -u )       shift
		      local user=$1
		      ;;
		    -p )       shift
		      local password=$1
		      ;;
		  esac
		  shift
		done

		local tries=200
		local tries2=200
		local pid="/var/lib/mysql/mysqld.pid"
		local db='mysql'
		echo $(date)  >> $LOG_FILE
		if [ "x$SERVICE" == "xmysql" -a ! -f /etc/init.d/mysql ]
		then
        	[ -f /etc/init.d/mysqld ] && SERVICE="mysqld"
		fi
		echo ":Using service $SERVICE $SECONDS"  >> $LOG_FILE
		stopService ${SERVICE} >> $LOG_FILE 2>&1
        [ -f "/var/lib/mysql/auto.cnf" ] && rm "/var/lib/mysql/auto.cnf";

		while [ "$tries" -gt 0 ]
		do
			if ! ps ax | $GREP -v grep | $GREP -q  mysql ;
			then
				break;
			fi
			sleep 0.5
			tries=$(($tries-1))
			stopService ${SERVICE} >> $LOG_FILE 2>&1
		done

		echo ":Mysql stopped $SECONDS" >> $LOG_FILE

		if ps ax | $GREP -v grep | $GREP -q  mysqld ;  then /usr/bin/killall mysqld 1>>$LOG_FILE 2>&1; /usr/bin/killall mysqld_safe 1>>$LOG_FILE 2>&1; fi
		${SERVICE_CMD} ${SERVICE} regenerate-config  >> $LOG_FILE 2>&1
		eval $MYSQLD_SAFE --skip-grant-tables --skip-networking --user=mysql  --pid-file=$pid >> $LOG_FILE 2>&1 &

		while [ ! -e $pid ]
		do
		    sleep 0.5
		    tries2=$(($tries2-1))
			if [ "$tries2" -lt 0  ]
			then
				echo "Time for wait mysqld-safe expired. result 4051" >> $LOG_FILE
				/usr/bin/killall mysqld 1>>$LOG_FILE 2>&1; /usr/bin/killall mysqld_safe 1>>$LOG_FILE 2>&1;
				startService ${SERVICE} 1>>$LOG_FILE 2>&1
				writeJSONResponseErr "result=>4051" "message=>Could not set password!";
				die -q
			fi
		done
		echo ":Mysql started mysqld-safe $SECONDS" >> $LOG_FILE
		val=$(sed 's/\.//' <<< $COMPUTE_TYPE_FULL_VERSION )
		[ -z "$val" ] && val=0 ;
               if [ "x$COMPUTE_TYPE" == "xmysql" -a $val -ge 57  ] ; then
                       $MYSQL $db --execute="UPDATE mysql.user SET authentication_string=PASSWORD('${password}') WHERE user='${user}';" 1>>$LOG_FILE 2>&1
        	       $MYSQL $db --execute="UPDATE mysql.user SET password_expired='N' WHERE user='${user}';" 1>>$LOG_FILE 2>&1
               else
                       $MYSQL $db --execute="UPDATE mysql.user SET password=PASSWORD('${password}') WHERE user='${user}';" 1>>$LOG_FILE 2>&1
               fi
		$MYSQL $db --execute="DELETE FROM mysql.user WHERE user = '';" 1>>$LOG_FILE 2>&1
		$MYSQL $db --execute="FLUSH PRIVILEGES;" 1>>$LOG_FILE 2>&1

		echo ":Mysql set password $SECONDS" >> $LOG_FILE
		/usr/bin/killall mysqld 1>>$LOG_FILE 2>&1; /usr/bin/killall mysqld_safe 1>>$LOG_FILE 2>&1;

		tries=200
		echo ":Stopping Mysql after set password $SECONDS" >> $LOG_FILE
		while [ "$tries" -gt 0 ]
		do
			if ! ps ax | $GREP -v grep | $GREP -q mysql ;
			then
				break;
			fi
			sleep 0.5
			tries=$(($tries-1))
			stopService ${SERVICE} 1>>$LOG_FILE 2>&1
		done

		echo ":Stopped Mysql after set password $SECONDS" >> $LOG_FILE
		startService ${SERVICE} 1>>$LOG_FILE 2>&1
		if ! ps ax | $GREP -v grep | $GREP -q  mysql ;
		then
			sleep 2
			startService ${SERVICE} 1>>$LOG_FILE 2>&1

		fi

		echo ":Started Mysql after set password $SECONDS" >> $LOG_FILE
                val=$(sed 's/\.//' <<< $COMPUTE_TYPE_FULL_VERSION )
                isDefPassLifetime=0
                defPassLifetime=$($MYSQL -u "${user}" -p"${password}" -NB -e "show global variables like 'default_password_lifetime'" 2>&1 | $SED -re '/mysql/d' | $SED -rne '/default_password_lifetime/s/default_password_lifetime\s+([0-9]+)/\1/p')
                [ ! -z "$defPassLifetime" ] && {
                    [[ $defPassLifetime -gt 0 ]] && isDefPassLifetime=1
                    mysqlusers=($($MYSQL $db -u "${user}" -p"${password}" -NB -e "select CONCAT('\'',user, '\'@\'', host,'\'') from user where user like 'root%'" 2>&1 | $SED -re '/mysql/d'))
                }

		[ -z "$val" ] && val=0 ;
		if [ "x$COMPUTE_TYPE" == "xmysql" -a $val -ge 57  ] ; then
		    $MYSQL -u "${user}" -p"${password}" $db --execute="SET PASSWORD FOR 'root'@'localhost' = PASSWORD('${password}');" 1>>$LOG_FILE 2>&1
		    $MYSQL -u "${user}" -p"${password}" $db --execute="SET PASSWORD FOR 'root'@'%' = PASSWORD('${password}');" 1>>$LOG_FILE 2>&1
                fi

                if [[ $isDefPassLifetime -gt 0 ]] ; then
                    for muser in ${mysqlusers[*]}; do
                        $MYSQL -u "${user}" -p"${password}" $db --execute="ALTER USER $muser PASSWORD EXPIRE INTERVAL ${defPassLifetime} DAY;" 1>>$LOG_FILE 2>&1
                    done
                fi

		echo ":Password updated $SECONDS" >> $LOG_FILE
		$CHKCONFIG --level 3 ${SERVICE} on 1>>$LOG_FILE 2>&1
}
