#!/bin/bash

pcubehome=`echo ~pcube`
export pcubehome

if . $pcubehome/sm.sh; then
   BIN_DIR=$UMROOT/bin/
else
   BIN_DIR=`dirname "$0"`	
   case $BIN_DIR in
    */) ;;
    *)  BIN_DIR=$BIN_DIR/ ;;
   esac
   BIN_FULL_DIR=`pwd`
   case $BIN_FULL_DIR in
    */) ;;
    *)  BIN_FULL_DIR=$BIN_FULL_DIR/ ;;
   esac
   BIN_FULL_DIR=$BIN_FULL_DIR$BIN_DIR
   # UMROOT must be the full path and not relative so ...
   UMROOT=$BIN_FULL_DIR../
fi

# verify UMROOT has a slash at the end
case $UMROOT in
 */) ;;
 *)  UMROOT=$UMROOT/ ;;
esac

LEG_DIR=${UMROOT}addons/bgpleg/
LEG_PATH=${LEG_DIR}bgpleg
CONFIG_PATH=${UMROOT}root/config/p3bgpleg.cfg
REST_PARAMS="$2 $3 $4 $5 $6 $7 $8 $9"
DOLLAR2="$2"

is_leg_running()
{
      # check whether is running
    case "`uname`" in
    SunOS) PSARG="-eaf"; ;;
    Linux) PSARG="uaxww"; ;;
	*) echo unknown architecture
	   PSARG="uaxwww" ;;
    esac
    [ `ps $PSARG | grep "bgpleg -launch" | grep -v grep | awk '{print $2}' | wc -l` -gt 0 ]
}

wait_for_leg_go_down () {
    # repeatedly probe the LEG during it's shutdown.
    
    echo "waiting for LEG to stop"
    echo -n "waiting.."
    # give the LEG some time to start up before polling
    sleep 1
    CNT=0
    # timeout = TM * DELAY seconds
    TM=30
    DELAY=2
    
    while [ $CNT -lt $TM ]; do
        is_leg_running || {
	    echo "LEG is down"
            return 0
	}	
	CNT=`expr $CNT + 1`
	sleep $DELAY
        echo -n "."
    done

    return 1
}





start_leg()
{
  leg_validate_cfg || exit 1
  # check if the LEG is running
  if is_leg_running; then
     echo "BGP LEG is already running, please stop it before re-starting"
     exit 1
  else
    echo "running the BGP LEG"
    ${LEG_PATH} -launch ${CONFIG_PATH} 2>&1 |logger -t SM -p daemon.notice  &
  fi

}

stop_leg()
{
    echo "stopping the BGP LEG"
    ${LEG_PATH} -exit || return 1;
    
    wait_for_leg_go_down || {
	echo "timeout expired - killing the LEG"
	case "`uname`" in
	SunOS) PSARG="-eaf"; ;;
	Linux) PSARG="uaxww"; ;;
	    *) echo unknown architecture
	       PSARG="uaxwww" ;;
	esac
	ps $PSARG | grep "bgpleg -launch" | \
	grep -v grep | awk '{print $2}'| xargs kill -9 >/dev/null 2>&1
    }

}

leg_status()
{
    ${LEG_PATH} -status
}

leg_summary()
{
    ${LEG_PATH} -sum
}

leg_summary_partial()
{
    if [ ! $DOLLAR2 ] ; then
	echo "No PE name provided"
	exit 2
    else
	${LEG_PATH} -pe-show ${REST_PARAMS}
    fi
}

leg_refresh_all()
{
    if [ ! $DOLLAR2 ] ; then
        ${LEG_PATH} -refresh all
    elif [ $DOLLAR2 = "--force-sync" ]; then
      if is_leg_running; then
        ${BIN_DIR}p3vpn --mpls-refresh-and-sync
      else
        echo "BGP LEG is not running - start it using p3bgp --start"
        exit 41
      fi
    else
        echo "Unknown parameter ${DOLLAR2}"
        exit 42
    fi      
}

leg_refresh()
{
    ${LEG_PATH} -refresh ${REST_PARAMS}
}

leg_debug()
{
    ${LEG_PATH} ${REST_PARAMS}
}

leg_restart()
{
    # verify root
    if [ -w /etc/passwd ]; then 
	stop_leg || exit 2
	
	curdir=`pwd`
	cd ${LEG_DIR}
	start_leg ||
	{
	    cd ${curdir}
	    exit 1
	}
	cd ${curdir}
    else
	echo "ERROR - you must run this command as root." 
	exit 7
    fi	
}

leg_validate_cfg()
{
    ${LEG_PATH} -validate ${CONFIG_PATH}
}


# set LD_LIBRARY_PATH if needed
if [ `echo $LD_LIBRARY_PATH | grep "addons/bgpleg" | wc -l` -eq 0 ]; then
    export set LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${UMROOT}addons/bgpleg
fi

case "$1" in
  --start)
	# verify root
	if [ -w /etc/passwd ]; then 
	    curdir=`pwd`
	    cd ${LEG_DIR}
	    start_leg || 
	    {
		cd ${curdir}
		exit 1
	    }
	    cd ${curdir}
	else
	    echo "ERROR - you must run this command as root."
	    exit 7
	fi
	;;
      
  --stop)
	  # verify root
	if [ -w /etc/passwd ]; then 
	    stop_leg || exit 2
	else
	    echo "ERROR - you must run this command as root."
	    exit 7;
	fi
	;;
	
  --restart)
	# verify root
	if [ -w /etc/passwd ]; then 
	    leg_restart || exit 6
	else
	    echo "ERROR - you must run this command as root."
	    exit 7;
	fi
	;;
	
  --status)
	leg_status || exit 2
	;;
	
  --show-all)
	leg_summary || exit 3
	;;
  --show)
	leg_summary_partial || exit 3
	;;	
  --refresh-all)
	leg_refresh_all || exit 4
        # avoid echoing "Command terminated successfully" twice
        exit 0
	;;
	
  --refresh)	
	leg_refresh || exit 5
	;;
	
  --load-config)	
	# verify root
	if [ -w /etc/passwd ]; then 
	    leg_validate_cfg || exit 8
	    echo "Configuration file is OK"
	    leg_restart || exit 6
	else
	    echo "ERROR - you must run this command as root."
	    exit 7
	fi
	;;
  --debug)
	leg_debug || exit 9
	;;	
  *)
	echo "Usage p3bgp [--start | --stop | --restart 
             --status | --show PE_NAME_PREFIX | --show-all |  --refresh-all [--force-sync]
             --refresh PE_NAME [PE_NAME ... ] ]
    --start            run the LEG
    --stop             stop the LEG's operation
    --restart          stop the LEG's operation and run it again
    --status           display a short status line for each PE
    --show-all         display a detailed status for all PEs
    --show             display a detailed status for PEs matching name prefix
    --refresh-all      send a refresh request or restart connection with 
                       ALL PEs in order to receive again all route updates. 
                       PEs will be retarted rather than refreshed,only if they
		       do not declare route-refresh capability upon connect.
    --force-sync       used together with --refresh-all. performs 
                       synchronization with SCE boxes after refresh is 
                       finished
    --refresh          specify a list of space delimited PE names in order
                       to receive again route updates from specific PEs
    --load-config      validate the configuration file and restart the LEG
    --help             display this message"
    ;;
	
esac

# if the script reached here then the command was succcessful (returned 0)
echo "Command terminated successfully" 
exit 0


