#!/bin/ksh
#
#	Copyright 06/03/98 Sun Microsystems, Inc.  All Rights Reserved.
#
# @(#)hasybase.sh	1.30 98/06/03 SMI
#
# hasybase - administrative command for HA-DBMS Sybase
#	(see hasybase_support(4), hasybase_config(4) )
#	     verifies and updates the HA-DBMS Sybase configuration files
#
#	This utility depends on the existence of the hadfconfig file.
#
# usage: hasybase [ -s ] operation [ server [ data ...] ]
#	-s:        silent mode
#	operation: one of list, insert, delete, update, start, stop
#	server:  name of server (not required for list operation)
#	data ...:  set of data fields for insert or update operation
#

# remember our name
argv0=`basename $0`

# Get the BASEDIR and PRODUCTDIR settings from the installed pkgs
_basedir_etc=`pkgparam SUNWsccf BASEDIR 2>/dev/null`
_basedir=`pkgparam SUNWscsyb BASEDIR 2>/dev/null`
_productdir=`pkgparam SUNWscsyb PRODUCTDIR 2>/dev/null`
_basedir=${_basedir:=""}
_productdir=${_productdir:="SUNWcluster"}

# Include dbms utilities file.
. ${_basedir}/${_productdir}/bin/dbms_utilities
 
# locations
HA_BIN=${_basedir}/${_productdir}/bin
FM_PROGS=${_basedir}/${_productdir}/ha/sybase
CT_PROGS=${_basedir}/${_productdir}/ha/sybase
ETC_CLUSTER=${_basedir_etc}/etc/opt/${_productdir}
PATH=$HA_BIN:$FM_PROGS:$CT_PROGS:/usr/bin:/usr/sbin
export PATH

# HA-DBMS file locations
HA_SUPPORT=${HA_FILES}/hasybase_support
HA_DATABASES="${HA_FILES}/hasybase_databases"
DS="sybase"
PREFIX="SUNWcluster.ha.${DS}"

# silent mode flag
silent=""

# Sybase locations
SYBTAB=/var/opt/sybase/sybtab

if [ -f ${ETC_CLUSTER}/conf/default_clustername ]; then
        HA_CLUSTER=`cat ${ETC_CLUSTER}/conf/default_clustername`
#	echo "Assuming a default cluster name of ${HA_CLUSTER}"
else
        echo "Cannot determine cluster name."
        exit 1
fi
 
TRAPSIGNALS="1 2 3 15"

#
# not_positive_numeric() -	not_positive_numeric string
#
#	Returns 1 if the string is numeric and positive, else returns 0
#
not_positive_numeric() {
	[ -z "$1" -o "`expr 0$1 : '.*'`" != "`expr 0$1 : '[0-9]*'`" -o \
		`expr 0$1 \<= 0` != "0" ]
}


#
# not_non_neg_numeric() -	not_non_neg_numeric string
#
#	Returns 1 if the string is numeric and positive or 0, else returns 0
#
not_non_neg_numeric() {
	[ -z "$1" -o "`expr 0$1 : '.*'`" != "`expr 0$1 : '[0-9]*'`" -o \
		`expr 0$1 \< 0` != "0" ]
}

# check_sybtab_line $server- find entry in $SYBTAB, return in sybtab_line
check_sybtab_line() {
        sybtab_line=`grep "^[    ]*$1:" $SYBTAB`

        if [ "$sybtab_line" = "" ] ; then
                errlog "${PREFIX}.hasybase.4000" "server \"$1\" not in $SYBTAB"
                return 1
       	else 
		return 0
        fi
}

parse_line(){

	db_line=$1

	# fields are separated by TABs, cut them apart

	mode=`echo "$db_line" | cut -s -f 1`
	server=`echo "$db_line" | cut -s -f 2`
	logical_host=`echo "$db_line" | cut -s -f 3`
	poll_cycle=`echo "$db_line" | cut -s -f 4`
	connect_cycle=`echo "$db_line" | cut -s -f 5`
	timeout=`echo "$db_line" | cut -s -f 6`
	restart_delay=`echo "$db_line" | cut -s -f 7`
	db_login=`echo "$db_line" | cut -s -f 8`
	runserver_file=`echo "$db_line" | cut -s -f 9`
        backup_server=`echo "$db_line" | cut -s -f 10`
        runbackup_file=`echo "$db_line" | cut -s -f 11`

}
	
hadb_validate_entry() {

	have_error=0
	parse_line "$1"

        associated_hosts=`hareg -q ${DS} -H | tr '\012' ' '`
        is_member "$logical_host" "$associated_hosts"
        if [ $? -ne 0 ]; then
                log "Logical Host \"$logical_host\" is not associated with service \"${DS}\" or not configured."
                log "Valid logical hostnames: \"$associated_hosts\"."
                have_error=1
        fi

	if not_positive_numeric $poll_cycle ; then
		errlog "Poll cycle time \"$poll_cycle\" should be a numeric value greater than 0"
		have_error=1
	fi

	if not_non_neg_numeric $connect_cycle ; then
		errlog "Connect cycle count \"$connect_cycle\" should be a numeric value greater than or equal to 0"
		have_error=1
	fi

	if not_non_neg_numeric $timeout ; then
		errlog "Time out \"$timeout\" should be a numeric value greater than or equal to 0"
		have_error=1
	fi
          
	if not_non_neg_numeric $restart_delay ; then
		errlog "Restart delay \"$restart_delay\" should be a numeric value greater than or equal to 0"
		have_error=1
	fi

	if [ `expr "//$db_login" : "//..*/"` = "0" ] ; then
		errlog "format of database login \"$db_login\" should be 'username/password' or '/'"
		have_error=1
	fi

	own_logical_host=`haget -f mastered | grep $logical_host`

	return $have_error
}



#
# hasybase_list filename - list the contents of the data file, skipping
#	comment lines
hasybase_list() {
	get_all ${DS}
}


# hasybase_insert filename server_name logical_host poll_time connect_cyle timeout \
#	restart_delay db_login [ runserver_file ]
# insert a record into filename 
#  
hasybase_insert() {
	server_name=$1; shift

	# make sure line for $server_name doesn't already exists in file
	line=$(get_instance "${DS}" "${server_name}")
	if [ "$line" != "" ] ; then
		log "server \"$server_name\" already in $BASEFILE:"
		abort "${PREFIX}.hasybase.4009" " --> $line"
	fi	

	# build the line for the new entry
	if [ $# -eq 7 ] ; then
		new_line="off	$server_name	$1	$2	$3	$4	$5	$6	$7		"
	elif [ $# -eq 9 ] ; then
		new_line="off	$server_name	$1	$2	$3	$4	$5	$6	$7	$8	$9"
	else
		log "parameters required for insert are: server_name host probe_cycle_time connect_cycle_count time_out restart_delay username/password run_server_file [ backup_server run_backup_server_file ]"
		usage
	fi

	parse_line "$new_line"
	get_hosts_and_links "$logical_host"
	hadb_validate_entry "$new_line"
	if [ $? -ne 0 ]; then
		abort "${PREFIX}.hasybase.4010" \
		"new hasybase server line failed sanity check"
	fi

        check_sybtab_line "$server_name" 
        if [ $? -ne 0 ]; then
		abort "${PREFIX}.hasybase.4020" \
		"sybtab file failed sanity check"
        fi

	add_unique_ha_instance "${DS}" "$new_line"
	if [ $? -ne 0 ]; then
                abort "${PREFIX}.hasybase.4020" \
                "Could not add entry to CCD for $server_name. Retry the operation."
        fi

	}


# hasybase_delete filename server_name
# delete a record for $server_name from $filename
hasybase_delete() {
	server_name=$1; shift
        inst_mode=$1

	line=$(get_instance "${DS}" "${server_name}" )
	if [ "$line" = "" ] ; then
		abort "${PREFIX}.hasybase.4030" \
		"no entry for server $1 in $BASEFILE - can't delete"
	fi

        # reject if fault monitor still running, only if not stopping
        if [[ "$inst_mode" != "stop" ]]; then
		mode=`echo "$line" | cut -s -f 1`
		if [ "$mode" = "on" ] ; then
			abort "${PREFIX}.hasybase.4040" \
	"cannot delete entry; stop $server_name fault monitor first"
		fi
	fi

	# delete all entries with $1 in the second column from the file
	remove ${DS} server $server_name
	[ $? -ne 0 ] && abort "${PREFIX}.hasybase.4050" \
			"$server_name could not be modified! Retry the operation."
}


# update an existing record in the data file ###################################
hasybase_update() {
	server_name=$1; shift

	line=$(get_instance "${DS}" "${server_name}")
	if [ "$line" = "" ] ; then
		abort "${PREFIX}.hasybase.4300" \
	"no entry for server $server_name in $BASEFILE - can't update"
	fi
	
	old_mode=`echo "$line" | cut -s -f 1`
        if [ "$old_mode" = "on" ] ; then
            abort "${PREFIX}.hasybase.4040" "cannot update entry; stop $server_name fault monitor first"
        fi

	if [ $# -eq 7 ] ; then
		new_line="$old_mode	$server_name	$1	$2	$3	$4	$5	$6	$7		"
	elif [ $# -eq 9 ] ; then
		new_line="$old_mode	$server_name	$1	$2	$3	$4	$5	$6	$7	$8	$9"
	else	
		log "parameters required for update are: server_name host probe_cycle_time connect_cycle_count time_out restart_delay username/password runserver_file [ backup_server run_backup_server_file ]"
		usage
	fi

	hadb_validate_entry "$new_line"
	if [ $? -ne 0 ]; then
		abort "${PREFIX}.hasybase.4310" \
		"new hasybase server line failed sanity check"
	fi

        check_sybtab_line "$server_name" 
        if [ $? -ne 0 ]; then
		abort "${PREFIX}.hasybase.4320" \
		"sybtab file failed sanity check"
        fi

	# delete the line with $server_name in the second column from the
	# file, and then insert $new_line in its place (replacing the line)
        hasybase_delete $server_name ""
        add_unique_ha_instance "${DS}" "$new_line"
	[ $? -ne 0 ] && abort "${PREFIX}.hasybase.4330" \
			"$filename could not be modified!"
	return 0
}


# hasybase_start_stop_run filename server ( start | stop )
# starts/stops fault monitoring for $server
# does not update $filename - see function hasybase_start_stop
hasybase_start_stop_run() {

	typeset return_value
	typeset -i i

	lhost=$(get_instance "${DS}" "$1" | awk '{print $3}')
	if [[ -z "$lhost" ]] ; then
		abort "${PREFIX}.hasybase.4400" \
		"no entry for server $1 in HA SYBASE CCD - can't $2"
	fi
	set -A hostarray $(get_logical_links "${lhost}")

	# Set no delay since we are manually starting fmon
        HA_FM_DBMSPROBE_DELAY=0; export HA_FM_DBMSPROBE_DELAY

	# call start/stop locally
	# log "$2 fault monitor for $1 on localhost..."
	${HA_BIN}/ha_dbms_call localhost $1 $2 sybase
	return_value=$?
        # call start remotely only if the local ha_dbms_call succeeded.
        (($return_value == 0)) && \
        if (( ${#hostarray[*]} > 0 )) ; then
                i=0
                while (( $i < ${#hostarray[*]} ))
                do
                        # log "$2 fault monitor for $1 on ${hostarray[i]} ... "
                        (( i=i+1 ))
                        ${HA_BIN}/ha_dbms_call ${hostarray[i]} $1 $2 sybase
                        (( i=i+1 ))
                        if [ "$?" != 0 ]; then
                                log "Failed to $2 fault monitor for $1 on ${hostarray[i]}"
                        fi
                done
        else
                log "No $2 of fault monitor for $1 on remote host."
        fi

	return $return_value
}

# hasybase_start_stop filename server ( start | stop )
# changes the on/off status for $server in $filename
# does not actually start or stop monitoring - see hasybase_start_stop_run
hasybase_start_stop() {
	# find the server
        line=$(get_instance_dynamic "${DS}" "${1}" )
	if [ "$line" = "" ] ; then
		abort "${PREFIX}.hasybase.4200" \
		"no entry for server $1 in $BASEFILE - can't $2"
	fi
	mode=`echo "$line" | cut -s -f 1`
	if [ "$2" = "start" ] ; then
		if [ "$mode" != "off" ] ; then
			abort "${PREFIX}.hasybase.4210" \
			"server $1 is not stopped in $BASEFILE!"
		fi

		# check the entry for the specific SQL server
		hadb_validate_entry "$line"
		if [ $? -ne 0 ] ; then
			abort "${PREFIX}.hasybase.4220" \
		"hasybase server line or sybtab file failed sanity check"
		fi

        	check_sybtab_line $1 
       		if [ $? -ne 0 ]; then
			abort "${PREFIX}.hasybase.4230" \
			"sybtab file failed sanity check"
        	fi
	else
		if [ "$mode" != "on" ] ; then
			abort "${PREFIX}.hasybase.4240" \
			"server $1 is not started in $BASEFILE!"
		fi
	fi
	
	         
	# update the entry in the file - find the old entry, and reply
	# off with on and vice versa
        if [ "$2" = "start" ] ; then
                new_line=`echo "$line" | sed 's/^off/on/'`
        else
                new_line=`echo "$line" | sed 's/^on/off/'`
        fi
        hasybase_delete $1 $2
        add_unique_ha_instance "${DS}" "$new_line"
        if [ $? -ne 0 ] ; then
                abort "${PREFIX}.hasybase.4250" \
		"$filename could not be modified!"
        fi

	return 0
}

get_hosts_and_links()
{

logical_host_name="$1"

set -A nativehosts $(haget -f mastered | tr '\012' ' ')
set -A foreignhosts $(haget -f not_mastered | tr '\012' ' ')

for i in ${nativehosts[*]}
do
	if [[ "$i" == "$logical_host_name" ]]; then
		HA_NATIVEHOST="$i"
		break
	fi
done
for i in ${foreignhosts[*]}
do
	if [[ "$i" == "$logical_host_name" ]]; then
		HA_FOREIGNHOST="$i"
		break
	fi
done

if [[ -n "$HA_NATIVEHOST" ]]; then
        res=`haget -f physical_hosts -h $HA_NATIVEHOST`
elif [[ -n "$HA_FOREIGNHOST" ]]; then
        res=`haget -f physical_hosts -h $HA_FOREIGNHOST`
else
        abort "${PREFIX}.hasybase.4140" "Cannot determine host members."
fi

HA_NATIVEHOST="${nativehosts}"
HA_FOREIGNHOST="${foreignhosts}"
ASYMLOGICALHOST="${nativehosts} ${foreignhosts}"

}

# ignore signals
catchsig() {
	echo "Caught signal; continuing."
}


#
# get_yes_or_no - prompt user for "y" or "n", and read answer. repeat if
#	answer is not "y" or "n". Returns the choice.
#	In silent mode, just returns "y"
#
get_yes_or_no() {
	if [ "$silent" = "y" ] ; then
		resp="y"
	else
		read resp
		while [ "$resp" != "y" -a "$resp" != "n" ]
		do
			echo
			echo '    Please respond "y" or "n" \c'
			read resp
		done
	fi
}


# log ... - if not silent, echo all parameters
log() {
	[ "$silent" != "y" ] && echo "$*"
}
# infolog ... - if not silent, echo all parameters
infolog() {
        typeset prefix
 
        prefix=$1
        shift
        [ "$silent" != "y" ] && log_info $prefix "$*"
}

# errlog - echo all parameters
errlog() {
        typeset prefix
 
        prefix=$1
        shift
        log_error $prefix "$*"

}

# abort ... - if not silent, echo all parameters. Then exit with status of 1
abort() {
        typeset prefix
 
        prefix=$1
        shift
        #[ "$silent" != "y" ] && print $prefix "$*"
        [ "$silent" != "y" ] && print "$*"
        exit 1
}

# usage - print command usage ################################################
usage() {
	log "usage: $argv0 [ -s ] operation [ server [ data ...] ]"
	log "  -s:        silent mode"
        log "  operation: one of list, insert, delete, update, start, stop"
	log "  server:  name of server (not required for list operation)"
        log "  data ...:  set of data fields for insert or update operation"
	exit 2
}


# check who we are - if we are not root, exit immediately
res=`id`
[ $? -ne 0 ] && abort "${PREFIX}.hasybase.4060" "Cannot execute id command"
[ `expr "$res" : "uid=0(root)"` != 11 ] && abort "${PREFIX}.hasybase.4070" \
		"$argv0 must be executed as root."

# check for -s parameter
while getopts s: c
do
	case $c in
		s) silent="y" ;;
		\?) usage ;;
	esac
done
shift `expr $OPTIND - 1`

export HA_DATABASES


# make sure we have a command
if [ $# -lt 1 ] ; then
	log "missing operation"
	usage
fi
command="$1"
shift
case "$command" in 
#	check|list)			 will_modify=0 ;;
	list)				 will_modify=0 ;;
	start|stop|insert|delete|update) will_modify=1 ;;
	*)				 log "invalid operation"
					 usage ;;
esac


# make sure HA is up
if (( $will_modify == 1 )); then
        clustm getstate $HA_CLUSTER >/dev/null 2>&1
	if [ $? -ne 0 ] ; then
                abort "${PREFIX}.hasybase.4100" \
	 "Cluster is not up; Run scadmin {startcluster|startnode} first"
	fi
 
	CMSTATE="`clustm getstate $HA_CLUSTER 2> /dev/null`"
	#make sure the host is not in reconfiguring 
        if [ "$CMSTATE" != "end" ]; then
		abort "${PREFIX}.hasybase.4110" \
 "This Sun Cluster is currently reconfiguring: hasybase command not allowed"
        fi
fi

# make sure Sybase service is registered and the state is on
if [ $will_modify -eq 1 ]; then
	reg=`hareg | grep sybase`
else
	reg=''
fi
if [ -z "$reg" -a $will_modify -eq 1 ] ;  then
	errlog "${PREFIX}.hasybase.4115" \
	"Sun Clusters HA-DBMS for SYBASE service is not registered."
	abort "${PREFIX}.hasybase.4120" \
	"You may run \"hareg -s -r sybase\" to register it."
fi

reg_state=`echo "$reg" | cut -f2 -s`
if [ "$reg_state" != "on" -a $will_modify -eq 1 ] ; then
	errlog "${PREFIX}.hasybase.4125" \
	"The state of Solstice HA-DBMS for SYBASE service is off."
	abort "${PREFIX}.hasybase.4130" \
	"You may run \"hareg -y sybase\" to turn the service on."
fi


# verify that we have server name, and can update ${HA_DATABASES}
if [ "$command" != "list" -a "$command" != "check" ] ; then
	if [ $# -lt 1 ] ; then
		log "server name missing"
		usage
	fi
	server=$1
	shift

fi

parms=$*

#BASEFILE=`basename ${HA_DATABASES}`
BASEFILE="CCD"
export BASEFILE


HA_LOCALHOST=`uname -n`

trap "catchsig" $TRAPSIGNALS

# run the appropriate function
case "$command" in
	list)       hasybase_list  ;;
	insert)     hasybase_insert $server $parms ;;
	delete)	    hasybase_delete $server $command ;;
	update)     hasybase_update $server $parms ;;
	start|stop) hasybase_start_stop $server $command
			hasybase_start_stop_run $server $command;;
	*)	    usage ;; # really already checked further up
esac

exit 0
