#!/bin/sh

# $Id$

#Start service ip interfaces.

#A stanza in the configuration should look something like:
# configdict['service_ips'] = {
#    'www-gccen'  : "gccensrv1.fnal.gov",
#    'pnfs-gccen' : "gccensrv2.fnal.gov",
#    'conf-gccen' : "gccensrv1.fnal.gov",
#    }

if [ `id -u` -ne 0 ]; then
   echo "Must be user root." 1>&2
   exit 1
fi

which enstore > /dev/null 2> /dev/null
if [ $? -ne 0 ]; then
    echo "The enstore command was not found." 1>&2
    exit 1
fi
PATH=/sbin:/usr/sbin:$PATH

#Make sure to set a timeout.
timeout='--timeout 3 --retries 3 --file-fallback'

#Get this configuration information only once.
raw_service_ips=`enstore conf $timeout --print service_ips 2>&1`
if [ $? -ne 0 ]; then
   echo "$raw_service_ips" | grep "KEYERROR" 2>&1 > /dev/null
   if [ $? -eq 0 ]; then
       echo "No entry for service alaises is found in configuration"
       exit 0
   else
       echo "Unable to obtain configuration information:" $raw_service_ips
   fi
fi

#Get just the unique alias names for now from all of the service IP info.
service_aliases=`echo "$raw_service_ips" | grep -v service_ips.status | tr "." " " | awk '{print $2}' | sort | uniq`
if [ "${service_aliases:-x}" = "x" ]; then
    echo "No entry for service alaises is found in configuration"
    exit 0
fi


#Format the interface information onto one line for each interface.
service_ip_map=`for alias in \`echo $service_aliases\`; do tmp_service_ip_info=\`echo "$raw_service_ips" | grep $alias\`; interface=\`echo "$tmp_service_ip_info" | grep interface | sed 's/^.*://'\`; host=\`echo "$tmp_service_ip_info" | grep host | sed 's/^.*://'\`; echo alias $alias "  " interface $interface "  " host $host ; done`

#Each line in $service_ip_map looks like:
#  alias www-gccen  interface www  host gccensrv1.fnal.gov

echo "$service_ip_map" |
while read line; do
   #Store into seperate variables the service alias and the shortname
   # of the node it should be started on and the interface name to use.
   service_alias=`echo $line | awk '{print $2}'`
   service_hostname=`echo $line | awk '{print $6}' | cut -f 1 -d "."`
   service_interface=`echo $line | awk '{print $4}'`

   #Get the hostname of the current machine.
   hostname=`hostname | cut -f 1 -d "."`

   #Start or stop the interface as necessary. 
   if [ $hostname = $service_hostname ]; then
      if [ _`uname` = _Linux ]; then
          ifup $service_interface
      elif [ _`uname` = _SunOS ]; then
          ifconfig $service_interface up
      fi
   else
      if [ _`uname` = _Linux ]; then
          ifdown $service_interface
      elif [ _`uname` = _SunOS ]; then
          ifconfig $service_interface down
      fi
   fi
done
