#!/bin/bash

### BEGIN INIT INFO
# Provides:         os4k_ilan
# Required-Start:    $syslog $remote_fs $network apache
# Should-Start: 
# Required-Stop:     $syslog $remote_fs
# Should-Stop:
# Default-Start:     3 5
# Default-Stop:      0 1 2 6
# Short-Description: various Linux configurations
# Description:       RC script for various configurations which cannot (or are not suitable to) be done by a config file
### END INIT INFO

#redirect stderr to stdout
exec 2>&1

#SLES15 protection - make sure script does nothing
echo "SLES15 - nothing to do."
exit 0

. /etc/rc.status
# import common variable and functions
. /opt/rcon/bin/sshr-base


#this is an option how to get dnsmasq configuration - not used now
#/opt/rcon/bin/sshr -c host_intl /usr/sbin/crm configure show rsc4k_dhcp_intl | egrep -o "fixed_host[fixed_host[0-9]=\"[^\"]*\""

HOST_FILE=/etc/hosts
ILAN_BEGIN="#ILAN hostnames grabbed from plt's etc hosts"
ILAN_END="#END OF ILAN hostnames grabbed from plt's etc hosts"

#########################################
# FUNCTIONS
#########################################

function is_ILAN_addr() {
	#omit host_intl because it is already in /etc/hosts
	[[ $1 =~ "$IPBASE" ]] && [[ ! $1 =~ "host_intl" ]] && return 0
	return 1
}

#(addr,"hostname1 hostname2 ...")
function add_to_hosts() {
	/usr/bin/ed $HOST_FILE 2>/dev/null <<GOGO
H
# remove entries with IP match
g/^$1/d
# go to the first line
1
# remove entries with hostname match
g/$2\W*$/d
# go to the last entry
$
# and add the new entry
.a
$*
.
w
GOGO
}

#reads stdin
function process_hosts() {
	while read LINE
	do
		if is_ILAN_addr "$LINE"
		then
			read -a ARR <<<$LINE
			ADDR=${ARR[0]}
			ARR=("${ARR[@]:1}")
			NAMES=""
			for i in ${ARR[@]}
			do
				NAMES="$NAMES $i $i."
			done
			# remove the whitespaces on the beginning
			NAMES=`echo $NAMES | sed -e 's/^\s\s*//g'`
			add_to_hosts $ADDR "$NAMES"
		fi
	done
	# remove obsolete labels
	sed -i "/^$ILAN_BEGIN/d" $HOST_FILE
	sed -i "/^$ILAN_END/d" $HOST_FILE
}


######################################
# MAIN 
######################################
# Reset status of this service
rc_reset
BASE=`basename $0`
case "$1" in
	start)
		/bin/echo -n "$BASE:"
		#default status is failed
		#my ILAN address
		IP="" # store IP
		ISIPDEFINED=$(ip addr show dev eth2 | grep 'inet ' 2>/dev/null | wc -l)

		if [ $ISIPDEFINED -lt 1 ];then
		  echo "Cannot get IP address of SOCO2 Platform."
		  echo "Check that eth2 interface is configured properly."
		  rc_failed 150	
		  rc_exit
		fi

		IP=$(ip addr show dev eth2 | grep 'inet ' | awk '{ print $2}' | awk -F '/' '{ print $1}')
		IPBASE=$(echo "$IP" | cut -d. -f1,2,3)
		OS4K_IP=$IPBASE.1

		#actualize os4kplt record in /etc/hosts
		/bin/echo -n " $OS4K_IP os4kplt"
		{
			cat <<GOGO
#first add line to the end of file
\$a

.
#no match -> stay at the end of file
g/os4kplt/
#now change/add the record
c
$OS4K_IP        os4kplt
.
#now delete the last empty line
$
g?^\s*\$?d
w
GOGO
} | ed -s /etc/hosts 2>&1 >/dev/null && /bin/echo -n " added to /etc/hosts."


		#get PLT's /etc/hosts and filter it for ILAN addresses
		hosts_list=`/opt/rcon/bin/sshr -c host_intl cat /etc/hosts`
		ret_val=$?
		if [ $ret_val -ne 0 ]
		then
			echo "Cannot get /etc/hosts content from PLT, sshr failed:$ret_val"
			#register cron to periodically run this script
			cat <(crontab -l | grep -v os4k_ilan ) <(echo "*/10 * * * * /etc/init.d/os4k_ilan start") | crontab -
			rc_failed 151
			rc_exit
		fi
		if [ -z "$hosts_list" ]
		then
			echo "PLT /etc/hosts empty ????"
			#register cron to periodically run this script
			cat <(crontab -l | grep -v os4k_ilan ) <(echo "*/10 * * * * /etc/init.d/os4k_ilan start") | crontab -
			rc_failed 151
			rc_exit
		fi
		echo "$hosts_list" | process_hosts
		#unregister this script from cron
		cat <(crontab -l | grep -v -e os4k_ilan -e '^#') | crontab -

		rc_status -v
		;;
	stop)
		rc_status -v
		;;
	restart)
		$0 stop
		$0 start
		rc_status -v
		;;
	status)
		rc_status -v
		;;
	*)
		echo "Usage: $0 {start|stop|status|restart}"
		rc_failed 1
		rc_exit
		;;
esac
			
rc_exit
