#!/bin/sh
#
# Copyright 1999 Sun Microsystems, Inc. All Rights Reserved
#
# @(#)cmg.sh	1.2 99/12/06 Sun Microsystems, Inc.
#

unset SSADM_ISATTY
SS_BINDIR=/opt/SUNWicg/SunScreen/bin
SS_LIBDIR=/opt/SUNWicg/SunScreen/lib
SS_ADMDIR=/opt/SUNWicg/SunScreen/ssadm
SS_ETCDIR=/etc/opt/SUNWicg/SunScreen
CONFIGS=$SS_ETCDIR/configs
ACTIVE=$SS_ETCDIR/.active
read SCREENNAME <$SS_ETCDIR/name

PATH="${SS_LIBDIR}:${SS_ADMDIR}:/usr/bin:/usr/sbin"
export PATH

set_num=31	# SI18N_ADMIN_SCRIPTS
LS()		# localize a string
{
	msg_num=$1; shift
	if [ -x ${SS_LIBDIR}/catgets ]
	then ${SS_LIBDIR}/catgets $set_num $msg_num "$*"
	else echo "$*\c"
	fi
}

set -e


usage()
{
    ustr=`LS 100 "Usage:"`
# LOCO: string of spaces having same length as "Usage:"
    uspc=`LS 101 "      "`
    pMsg=`LS 103 "primaryIPaddress"`
    sMsg=`LS 104 "secondaryIPaddress"`
    echo>&2 "$ustr  ssadm cmg status"
    echo>&2 "$uspc  ssadm cmg init_secondary <$pMsg>"
    echo>&2 "$uspc  ssadm cmg add_secondary <$sMsg>"

    exit 1;
}


init_secondary()
{
    masterIP=$1

    [ -n "$masterIP" ] || usage

    active -xf $domainarg cmg_setup
    scr="`edit $domainarg cmg_setup -c \"list Screen $SCREENNAME\"`"
    {
	echo "add screen \"$masterIP\" ADMIN_IP \"$masterIP\""
	echo "add screen $scr MASTER \"$masterIP\" ADMIN_CERTIFICATE NONE"
	echo "save"
    } | edit $domainarg cmg_setup
    activate -l $domainarg cmg_setup

    msg160=`LS 160 "This machine (%s) is now ready to be used as a CMG secondary machine."`
    msg161=`LS 161 "To add this machine to the CMG, run:"`
    msg162=`LS 162 "\"ssadm cmg add_secondary %s\" on the primary machine."`
    printf "$msg160\n" "$SCREENNAME"
    echo "$msg161"
    printf "$msg162\n" "<secondary's IP address>" #"$myIP"

    exit
}


add_secondary()
{
    slaveIP=$1

    [ -n "$slaveIP" ] || usage

    if [ ! -s $SSADM_TICKET_FILE ]
    then (umask 077; ssadm -G >$SSADM_TICKET_FILE)
    fi

    secondary=`ssadm -n -U "$SSADM_USER" -r "$slaveIP" $ssadmopt lib/screenname`
    echo "Found secondary Screen $secondary."
    ssadm -n -U "$SSADM_USER" -r "$slaveIP" $ssadmopt active -x > $CONFIGS/$domain/.cmg_join
    edit .cmg_join <<EOF
list screen
list interface
EOF
    echo>&2 "Note: this command is not implemented yet."
    exit 1
}


status()
{
    set +e
    echo ${SCREENNAME}:
    $SS_ADMDIR/active || exit
    cd ${ACTIVE}
    exec <Slaves
    while read name address status rest
    do echo ${name}:
       ssadm -n -t 10 -U "$SSADM_USER" -r $address $ssadmopt active
    done
}

SSADM_TICKET_FILE=$SS_ETCDIR/.cluster_ticket
export SSADM_TICKET_FILE

domain=default
domainarg=

if [ "$1" = status ]
then shift; status ${1+"$@"}; exit
fi

if [ ${SSADM_ACCESS_LEVEL:-WRITE} != "WRITE" ]
then msg150=`LS 150 "Access denied"`
     echo>&2 "ssadm cmg $1: $msg150"; exit 1
fi

case $1 in
init_secondary)	shift; init_secondary ${1+"$@"};;
add_secondary)	shift; add_secondary ${1+"$@"};;
*) usage;;
esac
