#!/bin/bash

VZLICVIEW="/usr/sbin/vzlicview"
MOTD="/etc/motd"
USER_MOTD="/etc/motd_user"
LICENSE="Virtuozzo License"

function get_field() {
	echo $1 | sed -e "s,.*$2=\",,g" -e "s,\".*,,g"
}

function update_motd() {
	local tmpmod=`mktemp /tmp/vzmod_XXXXXX 2>/dev/null`
	[ "x$tmpmod" = "x" ] && exit 1
	[ -f $USER_MOTD ] && cat $USER_MOTD > $tmpmod && echo "" >> $tmpmod
	echo "$*" >> $tmpmod
	mv -f $tmpmod $MOTD
	rm -f $tmpmod
}

function get_license_status() {
	[ ! -x $VZLICVIEW ] && return

	local out=`$VZLICVIEW 2>&1`
	local oneweek=$((60*60*24*7)) # In secs
	local today=`date +%s`
	local no_lic="No licenses installed."

	# Check for no licenses
	echo $out | grep "$no_lic" > /dev/null 2>&1
	[ $? -eq 0 ] && return

	# Get data
	local status=`get_field "$out" status`
	local key_number=`get_field "$out" key_number`
	local expiration=`get_field "$out" expiration`
	local expiration_date=`date --date="$expiration" +%s 2>/dev/null`
	local time_before_exp
	[ "x$expiration" = "xunlimited" ] && time_before_exp=$oneweek || time_before_exp=$((expiration_date - today))

	case "$status" in
		"ACTIVE"|"VALID")
			update_motd ""
			;;
		"EXPIRED"|"GRACED"|"INVALID"|"UNKNOWN"|"ERROR"|"INACTIVE")
			local status_lover=`echo $status | awk '{print tolower($0)}'`
			update_motd "$LICENSE $key_number is [0;31m$status_lover[0;39m."
			return
			;;
	esac
	if [ $time_before_exp -gt 0 -a $time_before_exp -lt $oneweek ]; then
		update_motd "$LICENSE $key_number will be [0;31mexpired[0;39m in $((time_before_exp/$((60*60*24)))) days."
	fi
}

get_license_status

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

for i in /etc/vz/ifup.d/*
do
	[ -x $i ] && $i $1
done
 
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 || exit 1
/bin/killall -SIGHUP agetty >/dev/null 2>&1
:
