#!/bin/bash
# 
# Copyright (c) 2012 - 2014, Hewlett-Packard Development Co., L.P. 
#
# Description: spread utility

SCRIPT_DIR="$(cd "$( dirname "$0")" && pwd)"

. $SCRIPT_DIR/mod_utils


stop_spread(){
	# stop spread
    local ret=0
	for ip in $*; do
        message 4 100 "Stopping spread on host $ip"
		ssh ${SSH_ARGS[@]} -i $ROOT_PEM $ip /etc/init.d/spreadd stop
        if [ $? -ne 0 ]; then
            (( ret = ret + 1 ))
            message 2 101 "Could not stop spread on $ip"
        fi
	done
    return $ret
}

start_spread(){
	# start spread
    local ret=0
	for ip in $*; do
        message 4 102 "Starting spread on host $ip"
   		ssh ${SSH_ARGS[@]} -i $ROOT_PEM $ip /etc/init.d/spreadd start
        if [ $? -ne 0 ]; then
            #  Try stopping then restarting...
            ssh ${SSH_ARGS[@]} -i $ROOT_PEM $ip /etc/init.d/spreadd stop
            ssh ${SSH_ARGS[@]} -i $ROOT_PEM $ip /etc/init.d/spreadd start
            if [ $? -ne 0 ]; then
               (( ret = ret + 1 ))
               message 2 103 "Could not start spread on $ip"
            fi
        fi
	done
    return $ret
}

rewrite_spreadd(){
	# modify /etc/sysconfig/spreadd SPREADARGS line

    local spreadd_location="/etc/sysconfig/spreadd"
    if [ "$OS" ==  "debian" ]; then
       spreadd_location="/etc/spreadd"
    fi;

    local ret=0
	for ip in $*; do
        message 4 104 "rewrite spread conf on host $ip"
		spread_id=`echo $ip | awk -F. '{printf "N%03i%03d%03d%03d", $1,$2,$3,$4}'`
		ssh ${SSH_ARGS[@]}  -i $ROOT_PEM $ip "cat ${spreadd_location} | sed \"s/^SPREADARGS=\\\"-n.*/SPREADARGS=\\\"-n $spread_id \\\${SPREADARGS}\\\"\"/ > /tmp/spread.reconf && cp /tmp/spread.reconf ${spreadd_location}"
        if [ $? -ne 0 ]; then
            (( ret = ret + 1 ))
            message 2 105 "rewrite spreadd failed on host $ip"
        fi
	done
    return $ret
}

write_vspread(){
    unset IFS	
	addrs=($*)

	echo "" > /tmp/myspread.txt
	for ip in ${addrs[@]}; do
		spread_id=`echo $ip | awk -F. '{printf "N%03i%03d%03d%03d", $1,$2,$3,$4}'`
		echo "Spread_Segment $ip:4803 {
		$spread_id    $ip {
		  $ip
		  127.0.0.1
		}
	}" >> /tmp/myspread.txt
	done
	echo "EventLogFile = /dev/null
	EventTimeStamp = \"[%a %d %b %Y %H:%M:%S]\"
	DaemonUser = spread
	DaemonGroup = verticadba
	DebugFlags = { EXIT }
	" >> /tmp/myspread.txt
}

reload_spread(){
	# this function should be called to help running spreads reload their configuration

    local spreadd_location="/etc/sysconfig/spreadd"
    if [ "$OS" ==  "debian" ]; then
       spreadd_location="/etc/spreadd"
    fi;

    local ret=0
    message 4 106 "reloading spread  on host $ip"
	ssh  ${SSH_ARGS[@]}  -i $ROOT_PEM $ip "source ${spreadd_location}; echo -e 'r\\n' | /opt/vertica/spread/bin/spmonitor \$SPREADARGS" 1>/dev/null
    if [ $? -ne 0 ]; then
            (( ret = ret + 1 ))
            message 2 107 "Could not reload spread config on host $ip"
    fi
    return $ret
}
