#!/bin/sh

# $Id: service_ips,v 1.8 2007/11/02 18:41:06 moibenko Exp $

#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'

#Incase information about service ips is longer than the python 
# pprint.pprint() function will print out. Get just the alias names now
# and we will extract the rest shortly one at a time.
service_aliases=`enstore conf $timeout --show  service_ips 2> /dev/null | grep -v status | sed -n "/^[{ ]'/p" | awk '{print $1}' | tr -d "{':"`

if [ "${service_aliases:-x}" = "x" ]; then
    echo "No entry for service alaises is found in configuration"
    exit 0
fi


#First, get the list of service IP from the configuration.
service_ip_map=`for alias in \`echo $service_aliases\`; do echo -n alias $alias " "; enstore conf $timeout --show service_ips $alias 2> /dev/null | sed 's/,/,\n/' | tr -d "{},:\'" | tr "\n" " "; echo; 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
