#!/bin/sh
#
# Copyright 1999 Sun Microsystems, Inc.
#
# @(#)ss_ha_sync_config.sh	3.7 99/07/12 Sun Microsystems
#
# usage: ss_ha_sync_config {activedir}
#

PATH="/opt/SUNWicg/SunScreen/bin:/usr/bin"
export PATH

SS_ADMDIR=/opt/SUNWicg/SunScreen/ssadm
SS_LIBDIR=/opt/SUNWicg/SunScreen/lib
SS_ETCDIR=/etc/opt/SUNWicg/SunScreen
read SCREENNAME </etc/opt/SUNWicg/SunScreen/name

HA_FILE="HA"
INTERFACE_FILE="Interface.in"

set -e

if [ "$1" = -r ]
then
	rm -rf $SS_ETCDIR/.ha_temp
	mkdir -m 0770 $SS_ETCDIR/.ha_temp
	chgrp sys $SS_ETCDIR/.ha_temp
	cd $SS_ETCDIR/.ha_temp
	tar -xof - skip.tar Configuration
	[ -f skip.tar ] && [ -f Configuration ] ||
	{ echo>&2 "HA synchronization data format error on $SCREENNAME"
	  exit 1
	}
	( cd /etc/skip;
	  rm -rf .old
	  mkdir .old
	  mv localid CAs certdb .old
	  tar -xf -
	) <skip.tar
	/usr/sbin/skipd_restart
	$SS_ADMDIR/activate <Configuration ||
	{ echo>&2 "HA synchronization error on $SCREENNAME."
	  exit 1
	}
	exit 0
fi

if [ ! -r $HA_FILE ]
then echo>&2 "High Availability is not configured, nothing to do."
     exit 1
fi

exec <$HA_FILE
IFS='" '
while read type name number addr
do if [ "$type" = "HA_HOST" -a "$number" -eq 1 ]
   then PRIME=$name
   fi
done

if [ "$PRIME" = "" ]
then echo>&2 "No primary HA host defined, nothing to do."
     exit 1;
fi

if [ "$PRIME" != "$SCREENNAME" ]
then echo "Not the primary HA host, nothing to do."
     exit 1
fi

HA_INTERFACE=`cat $INTERFACE_FILE |
    nawk '{ if ( $3 == "HA" ) print $1 }' | tr -d \" `

if [ "$HA_INTERFACE" = "" ]
then echo "No HA interface defined, nothing to do"
     exit 1
fi

#
# Syncronize all secondary HA hosts.
#

SYNC_HOSTS=`
 nawk '{if (( $1 == "HA_HOST") && ( $3 != 1 )) { print $4 } }' <$HA_FILE`

if [ "$SYNC_HOSTS" = "" ]
then echo "Notice: No secondary HA screens defined."
     exit 0
fi

# Copy SKIP config.
(cd /etc/skip; exec tar -cf - localid CAs certdb) >skip.tar

# Create the cluster ticket if necessary.
unset SSADM_ISATTY
SSADM_TICKET_FILE=$SS_ETCDIR/.cluster_ticket
export SSADM_TICKET_FILE
if [ ! -s $SSADM_TICKET_FILE ]
then (umask 077; ssadm -G >$SSADM_TICKET_FILE)
fi

exec <$HA_FILE
while read type name number addr
do
    [ "$type" = "HA_HOST" -a "$number" -ne 1 ] || continue

    echo "Synchronizing configurations on $name"

    # check if the target HA system is responding to commands
    if ssadm -n -r $addr -t 30 sys_info >/dev/null
    then
	tar -cf - skip.tar Configuration |
	ssadm -b -r $addr -t 30 lib/ss_ha_sync_config -r ||
	echo>&2 "Error: synchronizing configurations with $name"
    else
	# warn the user that the HA host is down
	echo "Warning: HA host $name is not responding."
    fi
done
