#!/bin/bash

[ -x /sbin/ip ] || exit 0

scriptname=$(basename $0)
pidfile="/tmp/${scriptname}"

exec 200>${pidfile}
flock -n 200 || exit 1
pid=$$
echo ${pid} 1>&200

IPS=$(/sbin/ip -o addr show scope global | /usr/bin/awk '{gsub(/\/.*/, " ", $4); print $4}')
DELIM=""
for IP in ${IPS}; do
	READABLE_IPS="${READABLE_IPS}${DELIM}${IP}"
	DELIM=", "
done
sed -i "s/\((IP\:\)[^)]*)/\1 ${READABLE_IPS})/" /etc/issue

sed -i '/Web Control Panel/d' /etc/issue
sed -i '/http/d' /etc/issue
cat -s /etc/issue > /etc/issue.tmp
echo "" >> /etc/issue.tmp
mv /etc/issue.tmp /etc/issue

UI_CFG=/etc/nginx/conf.d/vstorage-ui-backend.conf
if [ ! -f $UI_CFG ] ; then
	exit 0
fi

INIT_FILE="/etc/vstorage/motd"
DELIM="\n"
PORT=8888
IFACES=""

function tcp_port_on {
	ip=$1
	port=$2
	iface=`/sbin/ip -o addr show scope global | grep ${ip} -m 1 | /usr/bin/awk '{gsub(/\/.*/, " ", $2); print $2}'`
	timeout 1 bash -c "cat < /dev/tcp/${ip}/${port}"
	return $?
}

for IP in $IPS ; do
	if [ "${ADDR}" == "${PORT}" ]; then
		if [ `tcp_port_on ${IP} ${PORT}` == "yes" ]; then
			READABLE_ADDRS="${READABLE_ADDRS}${DELIM}http\:\/\/${IP}\:${PORT}"
			IFACE=`/sbin/ip -o addr show scope global | grep ${IP} -m 1 | /usr/bin/awk '{gsub(/\/.*/, " ", $2); print $2}'`
			IFACES="${IFACES}${DELIM}${IFACE}"
		fi
	fi
done

if [ -z ${READABLE_ADDRS} ]; then
	[ -f "${INIT_FILE}" ] && IFACES=`cat ${INIT_FILE}`
	for IFACE in ${IFACES}; do
		IP=`/sbin/ip -o addr show scope global | grep ${IFACE} -m 1 | /usr/bin/awk '{gsub(/\/.*/, "", $4); print $4}'`
		[ -z ${IP} ] && continue
		READABLE_ADDRS="${READABLE_ADDRS}${DELIM}http\:\/\/${IP}\:${PORT}"
	done
fi

grep -q "Web Control Panel" /etc/issue || sed -i 's#\\t#Web Control Panel is available on the following addresses\: \n\n\\t#' /etc/issue || exit 1
sed -i "s/\(Web Control Panel is available on the following addresses\:\)[^)]*/\1\n${READABLE_ADDRS}/" /etc/issue || exit 1
echo ${IFACES} > ${INIT_FILE}
/bin/killall -SIGHUP agetty >/dev/null 2>&1
:
