#!/bin/bash

# All files in this package is subject to the GPL v2 license
# More information is in the COPYING file in the top directory of this package.
# Copyright (C) 2011 Severalnines

# Also see CREDITS, many thanks to Timothy Der (randomorzero.wordpress.com)
# for the work on the makecfg, mysqlckk, and haproxy.cfg.tmpl

LOCKFILE="/tmp/s9s_change_passwd.lock"

function init
{
    FILES=`ls /etc/cmon.cnf 2>/dev/null`
    FILES2=`ls /etc/cmon.d/*.cnf 2>/dev/null`
    FILES="$FILES $FILES2"
    configfile=""
    for f in $FILES
    do
	X=`grep -l cluster_id=${CLUSTER_ID} $f 2>&1 `
	if [ $? -eq 0 ]; then
            source $f
            configfile=$f
        fi
    done

    if [ -z "$configfile" ]; then
        echo "No matching configuration file found having cluster_id=${CLUSTER_ID}"
        exit 1
    fi
    source $configfile;

    CMON_DB_HOST=127.0.0.1
    CMON_DB_PORT=$mysql_port
    CMON_USER=cmon
    CMON_DB_DB=cmon
#    CMON_PASSWORD=$mysql_password
    MYSQL_BIN=$mysql_basedir/bin/mysql
    MYSQL_BIN2=$mysql_bindir/mysql
    CONNECT_TIMEOUT=10
    CLUSTER_TYPE=$type
    MYSQL_OPTS="--connect-timeout=$CONNECT_TIMEOUT"
    OSUSER=$USER
    JOBID=0

    if [ "$OSUSER" != "root" ]; then
	echo "must be executed as 'root' or with 'sudo'"
	exit 1
    fi
}

function log_job_message
{
    MSG=$1
    EXIT_CODE=$2
    if [ -z "$EXIT_CODE" ]; then
	EXIT_CODE=1
    fi
    QUERY="INSERT INTO cmon_job_message(cid, jobid,message,exit_code,report_ts) VALUES($CLUSTER_ID,$JOBID,\"$MSG\",$EXIT_CODE,now())"
    if [ $JOBID -ne 0 ]; then
	$MYSQL_BIN  -B -N  --user=$CMON_USER --password=$CMON_PASSWORD --database=$CMON_DB_DB --host=$CMON_DB_HOST --port=$CMON_DB_PORT  -e "$QUERY" 2>&1 >/tmp/err.log
    else
	if [ $EXIT_CODE -ne 0 ]; then
	    echo ""
	    echo "Failed: $MSG"
	fi
    fi
}

function log_job
{
    STATUS=$1
    STATUS_TXT=$2
    EXIT_CODE=$3
    QUERY="UPDATE cmon_job SET status='$STATUS', status_txt='$STATUS_TXT', exit_code=$EXIT_CODE, report_ts=NOW()  WHERE cid=$CLUSTER_ID AND jobid=$JOBID"
    if [ $JOBID -ne 0 ]; then
	$MYSQL_BIN  -B -N  --user=$CMON_USER --password=$CMON_PASSWORD --database=$CMON_DB_DB --host=$CMON_DB_HOST --port=$CMON_DB_PORT  -e "$QUERY" 2>&1 >/tmp/err.log
    fi
}


function remote_copy()
{
   srcfile=$1
   desthost=$2
   destfile=$3
   printf "%-4s: Copying '%s' " "$desthost" "$srcfile"
   scp $SSH_OPTS2 $srcfile $SSH_USER@$desthost:$destfile >> $HOME/s9s_deploy.log  2>/dev/null
   if [ $? -eq 0 ]; then
      log_job_message "copying file $srcfile --> $desthost:$destfile" 0
      printf "\033[32m[ok]\033[0m\n"
      return 0
   else
      log_job_message "copying file $srcfile --> $desthost:$destfile" 1
      log_job 'FAILED' 's9s_haproxy failed' 1
      printf "\033[31m[failed]\033[0m\n"
      exit 1
   fi
}

function remote_cmdx()
{
   desthost=$1
   xcommand=$2
   printf "%-4s: Executing '%s'" "$desthost" "$xcommand"
   ssh -q $SSH_OPTS $SSH_USER@$desthost "$SUDO $xcommand "
   if [ $? -eq 0 ]; then
      log_job_message "$desthost: Executed $xcommand" 0
      printf "\033[32m[ok]\033[0m\n"
      return 0
   else
      log_job_message "command failed: $xcommand" 1
      log_job 'FAILED' 'backup failed' 1
      printf "\033[31m[failed]\033[0m\n"
      exit 1
   fi
}

function remote_cmd_nofail()
{
   desthost=$1
   xcommand=$2
   printf "%-4s: Executing '%s'" "$desthost" "$xcommand"
   ssh -q $SSH_OPTS $SSH_USER@$desthost "$SUDO $xcommand "  >> $HOME/s9s_deploy.log 2>&1
   ret=$?
   log_job_message "$desthost: Executed $xcommand" 0
   printf "\033[32m[ok]\033[0m\n"
   return $ret
}

function remote_cmd()
{
   desthost=$1
   xcommand=$2
   MAX_RETRIES=1
   printf "%-4s: Executing '%s' " "$desthost" "$xcommand"
   retry=0
   while [ $retry -lt $MAX_RETRIES ];
   do
      x=`ssh -q $SSH_OPTS $SSH_USER@$desthost "$SUDO $xcommand " 2>&1  >> $HOME/s9s_deploy.log`
      if [ $? -eq 0 ]; then
	  log_job_message "$desthost: Executed $xcommand" 0
          printf "\033[32m[ok]\033[0m\n"
          return 0
      fi
      retry=`expr $retry + 1`
      printf "\033[31m[failed: retrying ${retry}/${MAX_RETRIES}]\033[0m\n"
      ssh -q $SSH_OPTS $SSH_USER@$desthost " sync " 2>&1  >> $HOME/s9s_deploy.log
      sleep 1
   done
   log_job_message "FAILED: ${desthost}@${xcommand}" 1
   printf "\033[31m[failed]\033[0m\n"
   echo $x
   echo 'The following command failed:'
   echo "ssh -q $SSH_OPTS $SSH_USER@$desthost \" $xcommand \""
   echo 'Try running the command on the line above again, contact http://support.severalnines.com/ticket/new, attach the output from deploy.sh and the error from running the command to the Support issue.'
   exit 1
}


function remote_cmd3()
{
   desthost=$1
   xcommand=$2
   printf "%-4s: Executing '%s' " "$desthost" "$xcommand"
   ssh -nq -tt $SSH_OPTS $SSH_USER@$desthost "$SUDO $xcommand "   >> $HOME/s9s_deploy.log 2>&1
   if [ $? -eq 0 ]; then
       log_job_message "$desthost: Executed $xcommand" 0
       printf "\033[32m[ok]\033[0m\n"
       return 0
   else
       printf "\033[31m[failed]\033[0m\n"
       log_job_message "FAILED: ${desthost}@${xcommand}" 1
       exit 1
   fi
}

function remote_cmd_getreply()
{
   desthost=$1
   xcommand=$2
   x=`ssh -q $SSH_OPTS $SSH_USER@$desthost "$SUDO $xcommand"`
   if [ $? -ne 0 ]; then
       echo ""
   fi
   x=`echo $x | grep -v "password"`
   echo "OK"
}


function load_opts
{
    local CLUSTER_ID=$1
    echo "load opts $CLUSTER_ID"
    OS=`$MYSQL_BIN -N -B -A --user=$CMON_USER --password=$CMON_PASSWORD --database=$CMON_DB_DB --host=$CMON_DB_HOST --port=$CMON_DB_PORT -e "select value from cmon_configuration where param='OS' AND cid=$CLUSTER_ID" 2>/dev/null`
    CONFIGDIR=`$MYSQL_BIN -N -B -A --user=$CMON_USER --password=$CMON_PASSWORD --database=$CMON_DB_DB --host=$CMON_DB_HOST --port=$CMON_DB_PORT -e "select value from cmon_configuration where param='CONFIGDIR' AND cid=$CLUSTER_ID" 2>/dev/null`
    MYSQL_PORT=`$MYSQL_BIN -N -B -A --user=$CMON_USER --password=$CMON_PASSWORD --database=$CMON_DB_DB --host=$CMON_DB_HOST --port=$CMON_DB_PORT -e "select value from cmon_configuration where param='MYSQL_PORT' AND cid=$CLUSTER_ID" 2>/dev/null`
    GALERA_PORT=`$MYSQL_BIN -N -B -A --user=$CMON_USER --password=$CMON_PASSWORD --database=$CMON_DB_DB --host=$CMON_DB_HOST --port=$CMON_DB_PORT -e "select value from cmon_configuration where param='GALERA_PORT' AND cid=$CLUSTER_ID" 2>/dev/null`
    MYSQL_BASEDIR=`$MYSQL_BIN -N -B -A --user=$CMON_USER --password=$CMON_PASSWORD --database=$CMON_DB_DB --host=$CMON_DB_HOST --port=$CMON_DB_PORT -e "select value from cmon_configuration where param='MYSQL_BASEDIR' AND cid=$CLUSTER_ID" 2>/dev/null`
    STAGING_DIR=`$MYSQL_BIN -N -B -A --user=$CMON_USER --password=$CMON_PASSWORD --database=$CMON_DB_DB --host=$CMON_DB_HOST --port=$CMON_DB_PORT -e "select value from cmon_configuration where param='STAGING_DIR' AND cid=$CLUSTER_ID" 2>/dev/null`
    MYSQL_SCRIPTDIR=`$MYSQL_BIN -N -B -A --user=$CMON_USER --password=$CMON_PASSWORD --database=$CMON_DB_DB --host=$CMON_DB_HOST --port=$CMON_DB_PORT -e "select value from cmon_configuration where param='SCRIPTDIR' AND cid=$CLUSTER_ID" 2>/dev/null`
    SSH_IDENTITY=`$MYSQL_BIN -N -B -A --user=$CMON_USER --password=$CMON_PASSWORD --database=$CMON_DB_DB --host=$CMON_DB_HOST --port=$CMON_DB_PORT -e "select value from cmon_configuration where param='SSH_IDENTITY' AND cid=$CLUSTER_ID" 2>/dev/null`
    SSH_USER=`$MYSQL_BIN -N -B -A --user=$CMON_USER --password=$CMON_PASSWORD --database=$CMON_DB_DB --host=$CMON_DB_HOST --port=$CMON_DB_PORT -e "select value from cmon_configuration where param='SSH_USER' AND cid=$CLUSTER_ID" 2>/dev/null`
    SSH_PORT=`$MYSQL_BIN -N -B -A --user=$CMON_USER --password=$CMON_PASSWORD --database=$CMON_DB_DB --host=$CMON_DB_HOST --port=$CMON_DB_PORT -e "select value from cmon_configuration where param='SSH_PORT' AND cid=$CLUSTER_ID" 2>/dev/null`
    SSH_OPTSX=`$MYSQL_BIN -N -B -A --user=$CMON_USER --password=$CMON_PASSWORD --database=$CMON_DB_DB --host=$CMON_DB_HOST --port=$CMON_DB_PORT -e "select value from cmon_configuration where param='SSH_OPTS' AND cid=$CLUSTER_ID" 2>/dev/null`
    AGENTLESS=`$MYSQL_BIN -N -B -A --user=$CMON_USER --password=$CMON_PASSWORD --database=$CMON_DB_DB --host=$CMON_DB_HOST --port=$CMON_DB_PORT -e "select value from cmon_configuration where param='AGENTLESS' AND cid=$CLUSTER_ID" 2>/dev/null`
    SUDO=`$MYSQL_BIN -N -B -A --user=$CMON_USER --password=$CMON_PASSWORD --database=$CMON_DB_DB --host=$CMON_DB_HOST --port=$CMON_DB_PORT -e "select value from cmon_configuration where param='SUDO' AND cid=$CLUSTER_ID" 2>/dev/null`
    XVENDOR=`$MYSQL_BIN -N -B -A --user=$CMON_USER --password=$CMON_PASSWORD --database=$CMON_DB_DB --host=$CMON_DB_HOST --port=$CMON_DB_PORT -e "select value from cmon_configuration where param='VENDOR' AND cid=$CLUSTER_ID" 2>/dev/null`
    OS_USER_HOME=`$MYSQL_BIN -N -B -A --user=$CMON_USER --password=$CMON_PASSWORD --database=$CMON_DB_DB --host=$CMON_DB_HOST --port=$CMON_DB_PORT -e "select value from cmon_configuration where param='OS_USER_HOME' AND cid=$CLUSTER_ID" 2>/dev/null`
    NETWORKLESS=`$MYSQL_BIN -N -B -A --user=$CMON_USER --password=$CMON_PASSWORD --database=$CMON_DB_DB --host=$CMON_DB_HOST --port=$CMON_DB_PORT -e "select value from cmon_configuration where param='NETWORKLESS' AND cid=$CLUSTER_ID" 2>/dev/null`
    CMON_HOSTNAME=`$MYSQL_BIN -N -B -A --user=$CMON_USER --password=$CMON_PASSWORD --database=$CMON_DB_DB --host=$CMON_DB_HOST --port=$CMON_DB_PORT -e "select value from cmon_configuration where param='CMON_HOSTNAME1' AND cid=$CLUSTER_ID" 2>/dev/null`

    if [ $? -ne 0 ]; then
        log_job_message "load opts failed"
        exit 1
    fi

    if [ -z "$MYSQL_PORT" ]; then
        log_job_message "MYSQL_PORT not set in Cluster Settings"
        exit 1
    fi

    if [ -z "$AGENTLESS" ]; then
	AGENTLESS=0
    fi
    MONITORED_MYSQL_PORT=`$MYSQL_BIN -N -B -A --user=$CMON_USER --password=$CMON_PASSWORD --database=$CMON_DB_DB --host=$CMON_DB_HOST --port=$CMON_DB_PORT -e "select value from cmon_configuration where param='MONITORED_MYSQL_PORT' AND cid=$CLUSTER_ID" 2>/dev/null`
    
    if [ "$MONITORED_MYSQL_PORT" = "" ] || [ "$MONITORED_MYSQL_PORT" = "NULL" ];  then
        MONITORED_MYSQL_PORT="3306"
    fi
    if [ -z "$SSH_USER" ]; then
        log_job_message "SSH_USER not set in Cluster Settings"
        exit 1
    fi

    if [ -z "$OS" ]; then
        log_job_message "OS not set in Cluster Settings"
        exit 1
    fi


    SSH_OPTS="-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -oNumberOfPasswordPrompts=0 -oConnectTimeout=10"
    if [ "$SSH_IDENTITY" = "" ]; then
	SSH_IDENTITY="-oIdentityFile=${OS_USER_HOME}/.ssh/id_rsa"
    else
	SSH_IDENTITY="-oIdentityFile=$SSH_IDENTITY"
    fi
    SSH_OPTS="-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -oNumberOfPasswordPrompts=0 -oConnectTimeout=10 $SSH_IDENTITY"
    SSH_OPTS2="-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -oNumberOfPasswordPrompts=0 -oConnectTimeout=10 $SSH_IDENTITY"
    if [ "$SSH_USER" != "root" ]; then
	SSH_OPTS=" -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -oNumberOfPasswordPrompts=0 -oConnectTimeout=10 $SSH_IDENTITY"
	if [ "$SUDO" = "" ] || [ "$SUDO" = "NULL" ];  then
           SUDO=sudo
        fi
    fi
    if [ "$SSH_PORT" = "" ] || [ "$SSH_PORT" = "NULL" ];  then
        SSH_PORT="22"
    fi
    SSH_OPTS="$SSH_OPTSX -p$SSH_PORT $SSH_OPTS"
    SSH_OPTS2="-P$SSH_PORT $SSH_OPTS"

}

function change_password_mysql
{
    local h=$1
    local user=$2
    local new_password=$3
    local old_password=$4
    new_password=$(printf '%q' $new_password)
    old_password=$(printf '%q' $old_password)
    if [ "$user" = "cmon" ]; then
	QUERY="UPDATE mysql.user SET password=password('$new_password') WHERE user='$user'; FLUSH PRIVILEGES;"
    else
	QUERY="UPDATE mysql.user SET password=password('$new_password') WHERE user='$user' AND password=password('${old_password}'); FLUSH PRIVILEGES;"
    fi

    echo "$h: executing: $QUERY"
   `$MYSQL_BIN -B -N --host=$h --port=$MONITORED_MYSQL_PORT --user=cmon --password=$CMON_PASSWORD --database=mysql -e "$QUERY"`
    if [ $? -ne 0 ]; then
	echo "Failed $QUERY"
	exit 1
    fi

}


function change_password_mysql_mycnf
{
    local h=$1
    local new_password=$2
    MYCNF=$CONFIGDIR/my.cnf
    new_password2=$(printf '%q' $new_password)
    remote_cmd $h "sed -i \"s/wsrep_sst_auth=.*/wsrep_sst_auth=\'root:$new_password2\'/\" $MYCNF"
    QUERY="SET GLOBAL wsrep_sst_auth='root:$new_password'"
    echo "$h: executing: $QUERY"
   `$MYSQL_BIN --host=$h --port=$MONITORED_MYSQL_PORT --user=cmon --password=$CMON_PASSWORD --database=mysql -e "$QUERY"`
    if [ $? -ne 0 ]; then
	echo "Failed $QUERY"
	exit 1
    fi
}


function change_password_mysql_mysqlchk
{
    local h=$1
    local new_password=$2    
    new_password=$(printf '%q' $new_password)
    MYSQLCHK=/usr/local/bin/mysqlchk.sh
    exist=$(remote_cmd_getreply $h "[ -f $MYSQLCHK ] && echo 'OK'")
    if [ "$exist" = "OK" ]; then
	remote_cmd $h "sed -i \"s/^MYSQL_PASSWORD=.*/MYSQL_PASSWORD=\'$new_password\'/\" $MYSQLCHK "
	remote_cmd $h "sed -i 's/^MYSQL_USERNAME=.*/MYSQL_USERNAME=root/g' $MYSQLCHK"
    fi
}


function change_password_cmoncnf
{
    local h=$1
    local new_password=$2
    new_password=$(printf '%q' $new_password)
    FILES=`ls /etc/cmon.cnf 2>/dev/null`
    FILES2=`ls /etc/cmon.d/*.cnf 2>/dev/null`
    FILES="$FILES $FILES2"
    for f in $FILES 
    do
	tmp_configfile=$f
	if [ "$h" != "$CMON_HOSTNAME" ]; then
            tmp_configfile=/etc/cmon.cnf
	fi
	remote_cmd $h "sed -i \"s/mysql_password=.*/mysql_password=\'$new_password\'/\" $tmp_configfile"
	remote_cmd $h "rm -rf ${configfile}*bak"
    done
}

function change_root_password_cmoncnf
{
    local h=$1
    local new_password=$2
    non_escaped=$new_password
    new_password=$(printf '%q' $new_password)
    tmp_configfile=$configfile
    FILES=`ls /etc/cmon.cnf 2>/dev/null`
    FILES2=`ls /etc/cmon.d/*.cnf 2>/dev/null`
    FILES="$FILES $FILES2"
    for f in $FILES 
    do
	if [ "$h" != "$CMON_HOSTNAME" ]; then
            tmp_configfile=/etc/cmon.cnf
	fi
	exist=$(remote_cmd_getreply $h "grep monitored_mysql_root $tmp_configfile")
	if [ "$exist" = "OK" ]; then
	    remote_cmd $h "sed -i \"s/monitored_mysql_root_password=.*/monitored_mysql_root_password=\'$new_password\'/\" $tmp_configfile"
	    remote_cmd $h "rm -rf ${configfile}*bak"
	else
	    remote_cmd $h "sh -c 'echo \"monitored_mysql_root_password='$new_password'\" >> $tmp_configfile '"
	    remote_cmd $h "sed -i \"s/monitored_mysql_root_password=.*/monitored_mysql_root_password=\'$new_password\'/\" $tmp_configfile"
	    remote_cmd $h "rm -rf ${configfile}*bak"
	fi
    done
}



function change_cmon_password
{
    LB_NODE_LIST=""
    args=`getopt p:s:P:h:i:N:n:j: $*`
    set -- $args
    for i
    do
        case "$i" in
            -p)
                CMON_PASSWORD="$2"; shift;
                shift;;
            -i)
                CLUSTER_ID="$2"; shift;
                shift;;
            -n)
                NEW_PASSWORD="$2"; shift;
                shift;;
            -j)
                JOBID="$2"; shift;
                shift;;
            --)
                shift; break;;
                esac
    done


    if [ -z "$CMON_PASSWORD" ]; then
        echo "s9s_change_passwd --cmon  -p <current cmon password> is missing"
	exit 1
    fi
    OLD_PASSWORD=$CMON_PASSWORD
    if [ -z "$CLUSTER_ID" ]; then
        echo "s9s_change_passwd --cmon  -i <cluster id> is missing"
	exit 1
    fi
    init

    if [ -z "$NEW_PASSWORD" ]; then
        echo "s9s_change_passwd --cmon  -n <new_password> is missing"
        exit 1
    fi


    if ! test -f $MYSQL_BIN; then
	if ! test -f $MYSQL_BIN2; then
	    echo "Could not find mysql client binary"
	    echo "Change MYSQL_BIN in beginning of the scipt"
	    exit 1
	fi
	MYSQL_BIN=$MYSQL_BIN2
    fi



    load_opts $CLUSTER_ID
    QUERY="select count(id) from cluster_state WHERE status!='STARTED'"
    c_cnt=`$MYSQL_BIN -B -N --host=$CMON_DB_HOST --port=$CMON_DB_PORT --user=cmon --password=$CMON_PASSWORD --database=$CMON_DB_DB -e "$QUERY"`
    
    if [ $c_cnt -ne 0 ]; then
	echo "Not all clusters are started. Aborting"
	exit 1
    fi
    
    QUERY="select group_concat(h.hostname SEPARATOR ' ') from mysql_server m, hosts h WHERE m.id=h.id and h.cid=m.cid and h.ping_status>0 and connected=1"
    mysql_hostnames=`$MYSQL_BIN -B -N --host=$CMON_DB_HOST --port=$CMON_DB_PORT --user=cmon --password=$CMON_PASSWORD --database=$CMON_DB_DB -e "$QUERY"`

    QUERY="select group_concat(h.hostname SEPARATOR ' ') from hosts h WHERE h.ping_status>0"
    all_hostnames=`$MYSQL_BIN -B -N --host=$CMON_DB_HOST --port=$CMON_DB_PORT --user=cmon --password=$CMON_PASSWORD --database=$CMON_DB_DB -e "$QUERY"`

    QUERY="select count(id) from hosts h WHERE h.ping_status>0"
    c_cnt=`$MYSQL_BIN -B -N --host=$CMON_DB_HOST --port=$CMON_DB_PORT --user=cmon --password=$CMON_PASSWORD --database=$CMON_DB_DB -e "$QUERY"`
    QUERY="select count(id) from hosts h"
    a_cnt=`$MYSQL_BIN -B -N --host=$CMON_DB_HOST --port=$CMON_DB_PORT --user=cmon --password=$CMON_PASSWORD --database=$CMON_DB_DB -e "$QUERY"`

    if [ $a_cnt -ne $c_cnt ]; then
	echo "Not all hosts are reachable. Aborting"
	exit 1
    fi


    if [ -z "$mysql_hostnames" ]; then
	echo "No hostnames found."
       exit 1
    fi

    if [ "$mysql_hostnames" = "NULL" ]; then
       echo "No hostnames found."
       exit 1
    fi


    if [ -z "$all_hostnames" ]; then
       echo "No hostnames found."
       exit 1
    fi

    if [ "$all_hostnames" = "NULL" ]; then
       echo "No hostnames found."
       exit 1
    fi

    mysql_hostnames="$mysql_hostname $mysql_hostnames"
    echo $mysql_hostnames

    for h in $mysql_hostnames
    do
	change_password_mysql $h cmon $NEW_PASSWORD $OLD_PASSWORD
	F=/usr/bin/wsrep_notify_cc
	exist=$(remote_cmd_getreply $h "[ -f $F ] && echo 'OK'")
	if [ "$exist" = "OK" ]; then
	    new_password=$(printf '%q' $NEW_PASSWORD)
	    remote_cmd $h "sed -i \"s/^CMON_PASSWORD=.*/CMON_PASSWORD=\'$new_password\'/\" $F"	    
	fi
    done

    echo $all_hostnames
    for h in $all_hostnames
    do
	if [ $AGENTLESS -eq 1 ]; then
	    if [ "$hostname" = "$h" ]; then
		change_password_cmoncnf $h $NEW_PASSWORD
		remote_cmd_nofail $h "killall -9 cmon"
		sleep 1
		remote_cmd3 $h "/etc/init.d/cmon start 2>&1 >/dev/null"
	    fi
	else
	    change_password_cmoncnf $h $NEW_PASSWORD
	    remote_cmd_nofail $h "killall -9 cmon"
	    sleep 1
	    remote_cmd $h "/etc/init.d/cmon start 2>&1 >/dev/null"
	fi
	    
    done
    QUERY="UPDATE cmon_configuration SET value='$NEW_PASSWORD' WHERE param='CMON_PASSWORD' AND cid='$CLUSTER_ID'"

    `$MYSQL_BIN -N -B -A --user=$CMON_USER --password=$NEW_PASSWORD --database=$CMON_DB_DB --host=$CMON_DB_HOST --port=$CMON_DB_PORT -e "$QUERY"`
    if [ $? -ne 0 ]; then
	echo "Failed to set CMON_PASSWORD in cmon_configuration table, you can go into Cluster Settings in the web interface and set it"
	exit 1
    fi

    change_ui_password "cmon" "$NEW_PASSWORD"
    echo "Successfully changed 'cmon' password"
    exit 0
}



function change_root_password
{
    LB_NODE_LIST=""
    args=`getopt p:s:P:h:i:N:n:j:o: $*`
    set -- $args
    for i
    do
        case "$i" in
            -p)
                CMON_PASSWORD="$2"; shift;
                shift;;
            -i)
                CLUSTER_ID="$2"; shift;
                shift;;
            -o)
                OLD_PASSWORD="$2"; shift;
                shift;;
            -n)
                NEW_PASSWORD="$2"; shift;
                shift;;
            -j)
                JOBID="$2"; shift;
                shift;;
            --)
                shift; break;;
        esac
    done


    if [ -z "$CMON_PASSWORD" ]; then
        echo "s9s_change_passwd --root  -p <cmon password> is missing"
	exit 1
    fi
    
    if [ -z "$OLD_PASSWORD" ]; then
        echo "s9s_change_passwd --root  -o <old_root_password> is missing"
	exit 1
    fi
    
    if [ -z "$CLUSTER_ID" ]; then
        echo "s9s_change_passwd --root  -i <cluster id> is missing"
	exit 1
    fi

    init

    if [ -z "$NEW_PASSWORD" ]; then
        echo "s9s_change_passwd --root  -n <new_root_password> is missing"
        exit 1
    fi



    load_opts $CLUSTER_ID
    
    QUERY="select count(id) from cluster_state WHERE status!='STARTED'"
    c_cnt=`$MYSQL_BIN -B -N --host=$CMON_DB_HOST --port=$CMON_DB_PORT --user=cmon --password=$CMON_PASSWORD --database=$CMON_DB_DB -e "$QUERY"`
    
    if [ $c_cnt -ne 0 ]; then
	echo "Not all clusters are started. Aborting"
        exit 1
    fi
    
    QUERY="select group_concat(h.hostname SEPARATOR ' ') from mysql_server m, hosts h WHERE m.id=h.id and h.cid=m.cid and h.ping_status>0 and connected=1 and m.cid=$CLUSTER_ID"
    mysql_hostnames=`$MYSQL_BIN -B -N --host=$CMON_DB_HOST --port=$CMON_DB_PORT --user=cmon --password=$CMON_PASSWORD --database=$CMON_DB_DB -e "$QUERY"`

    if [ -z "$mysql_hostnames" ]; then
       echo "No hostnames found."
       exit 1
    fi

    if [ "$mysql_hostnames" = "NULL" ]; then
       echo "No hostnames found."
       exit 1
    fi

    mysql_hostnames="$mysql_hostname $mysql_hostnames"
    echo $mysql_hostnames

    for h in $mysql_hostnames
    do
	change_password_mysql $h root $NEW_PASSWORD $OLD_PASSWORD
    done


    for h in $mysql_hostnames
    do
	if [ $AGENTLESS -eq 1 ]; then
	    if [ "$hostname" = "$h" ]; then
		change_root_password_cmoncnf $h $NEW_PASSWORD
		remote_cmd_nofail $h "killall -9 cmon"
		sleep 1
		remote_cmd3 $h "/etc/init.d/cmon start 2>&1 >/dev/null"
	    fi
	else
	    change_root_password_cmoncnf $h $NEW_PASSWORD
	    remote_cmd_nofail $h "killall -9 cmon"
	    sleep 1
	    remote_cmd $h "/etc/init.d/cmon start 2>&1 >/dev/null"
	fi
    done

    QUERY="select group_concat(hostname SEPARATOR ' ') from mysql_server m WHERE  m.cid=$CLUSTER_ID"
    mysql_hostnames=`$MYSQL_BIN -B -N --host=$CMON_DB_HOST --port=$CMON_DB_PORT --user=cmon --password=$CMON_PASSWORD --database=$CMON_DB_DB -e "$QUERY"`
    for h in $mysql_hostnames
    do
	change_password_mysql_mysqlchk $h $NEW_PASSWORD
	case $CLUSTER_TYPE in
	    galera)
		change_password_mysql_mycnf $h $NEW_PASSWORD
		;;
	    *)
		;;
	esac
    done


    QUERY="UPDATE cmon_configuration SET value='$NEW_PASSWORD' WHERE param='ROOT_PASSWORD' AND cid='$CLUSTER_ID'"
    `$MYSQL_BIN -N -B -A --user=$CMON_USER --password=$CMON_PASSWORD --database=$CMON_DB_DB --host=$CMON_DB_HOST --port=$CMON_DB_PORT -e "$QUERY"`
    if [ $? -ne 0 ]; then
	echo "Failed to set ROOT_PASSWORD in cmon_configuration table, you can go into Cluster Settings in the web interface and set it"
	exit 1
    fi
    echo "Successfully changed root password"
    exit 0

}

function change_ui_password()
{
    user="$1"
    new_password="$2"
    db_credentials=""
    [[ -f /var/www/clustercontrol/bootstrap.php ]] && db_credentials="/var/www/clustercontrol/bootstrap.php"
    [[ -f /var/www/html/clustercontrol/bootstrap.php ]] && db_credentials="/var/www/html/clustercontrol/bootstrap.php"
    if [[ ! -z $db_credentials ]]; then
        echo "Found ClusterControl UI database credentials, $db_credentials"
        sed -i "s|^define('DB_LOGIN'.*|define('DB_LOGIN', '${user}');|g" $db_credentials
        sed -i "s|^define('DB_PASS'.*|define('DB_PASS', '${new_password}');|g" $db_credentials
        echo "ClusterControl UI database access credentials changed"
    else
        echo "** Unable to find ClusterControl UI database credentials (/var/www/clustercontrol/bootstrap.php | /var/www/html/clustercontrol/bootstrap.php)"
        echo "** ClusterControl UI database access credentials have not been changed"
    fi
    db_credentials=""
    [[ -f /var/www/cmonapi/config/database.php ]] && db_credentials="/var/www/cmonapi/config/database.php"
    [[ -f /var/www/html/cmonapi/config/database.php ]] && db_credentials="/var/www/html/cmonapi/config/database.php"
    if [[ ! -z $db_credentials ]]; then
        echo "Found ClusterControl REST API database credentials, $db_credentials"
        sed -i "s|^define('DB_USER'.*|define('DB_USER', '${user}');|g" $db_credentials
        sed -i "s|^define('DB_PASS'.*|define('DB_PASS', '${new_password}');|g" $db_credentials
        echo "ClusterControl REST API database access credentials changed"
    else
        echo "** Unable to find ClusterControl REST API database credentials (/var/www/cmonapi/config/database.php | /var/www/html/cmonapi/database.php)"
        echo "** ClusterControl REST API database access credentials have not been changed"
    fi
}

if [ ! -e $LOCKFILE ]; then
    trap "rm -f $LOCKFILE; exit" INT TERM EXIT
    touch $LOCKFILE
    case $1 in
	--cmon)
	    change_cmon_password  $2 $3 $4 $5 $6 $7 $8 $9
	    ;;
	--root)
	    change_root_password  $2 $3 $4 $5 $6 $7 $8 $9
	    ;;
	*)
	    echo "Usage: "
	    echo "s9s_change_password  --[cmon|root] "
	    exit 1
	    ;;
    esac
    rm $LOCKFILE
    trap - INT TERM EXIT
fi

