#!/bin/sh
THIS_SCRIPT=`basename $0`
function Usage()
{
  cat <<EOT
# DESCRIPTION
#   A simple script to demonstrate server ip configuration ultility
# 
# SYNOPSIS
#   $THIS_SCRIPT [<Interface> <ServNewIpAddr> [NetMask]]
#
# EXAMPLE
#   $THIS_SCRIPT
#   Display current network configuration
#
#   $THIS_SCRIPT eth0 192.168.0.3
#   Set ip to 192.168.0.3/24 for interface eth0
#
#   If not specified, the default mask will be 255.255.255.0
#
EOT
}

#
# definitions
#
CTL_APP=/home/tc/bin/tc-client-control
SVR_APP=/home/tc/bin/tc-client-control-server
LOG_FILE=/tmp/tcifconfig.log

#===============================================================================
function msg()
{
  echo $@
  echo $@ >>$LOG_FILE
}
date "+%F %T" > $LOG_FILE

#===============================================================================
msg "Parsing arguments..."
case $# in 
  0)
    ifconfig
    exit 0
    ;;
  2|3)
    nif=$1
    ip=$2
    mask=$3
    if [ "x$mask" == "x" ] ; then
      mask=255.255.255.0
    fi
    ;;
  *)
    Usage
    exit 1
    ;;
esac
msg "-- Interface name: $nif"
msg "-- Ip addr: $ip"
msg "-- Mask: $mask"


#===============================================================================
#
# step i
# send command to all client
#
msg "Notifying client server ip is about to be changed..."
$CTL_APP --cgsvrip $ip


#===============================================================================
#
# step ii
# set up network
#
msg "Setting up local ip..."
until [ "x$local_ip" == "x$ip" ] ; do
  ifconfig $nif $ip $mask
  local_ip=`ifconfig $nif | awk '/net / { x = $2 } END { print x }'`
  msg "-- Local ip: $local_ip"
  sleep 1
done


#===============================================================================
#
# step iii
# stop service
#
systemctl stop tcs-ccontrol-server


#===============================================================================
#
# step iv
# start service
#
systemctl start tcs-ccontrol-server

#===============================================================================
msg "retval: $retval"
exit $retval

