#!/bin/sh

# Copyright (C) 2009  Citrix Systems Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

# Script to write information about the guest to XenStore.
#
# Information collected (if --memory NOT passed in):
#   - Distribution name
#   - Distribution version (major and minor)
#   - Kernel version (uname)
#   - IP address for each Ethernet interface
#
# Information collected (if --memory IS passed in):
#   - memtotal
#   - memfree
#
# Memory stats are separated out because they change all the time
# and so we may not want to update them as frequently

LANG="C"
export LANG


XE_LINUX_DISTRIBUTION_CACHE=/var/cache/xe-linux-distribution

IPADDR_RE="\([[:digit:]]\{1,3\}\.\)\{3\}[[:digit:]]\{1,3\}"

export PATH=/usr/sbin:/usr/bin:/sbin:/bin
XENSTORE=${XENSTORE:-/usr/local/bin/xenstore}

XENSTORE_UPDATED=0

# parse command line opts

MEMORY_MODE=0 # do not update memory stats 
while [ $# -ge 1 ] ; do 
    if [ "$1" = "--memory" ] ; then
	MEMORY_MODE=1	# update only memory stats 
    fi
    shift
done

xenstore_write_cached() {
    key="$1" newval="$2"
    cache=/var/cache/xenstore/$key
    if [ -f $cache ] ; then
	# cache exists
	oldval=$(cat "$cache")
	if [ "$oldval" = "$newval" ] ; then
	    # value unchanged
	    return 0
	fi
    else
	# cache does not exist
	if [ -e $cache ] ; then 
	    # something (directory?) in its way
	    rm -rf $cache
	fi
    fi
    
    # try to write and update cache if successfull
    if $XENSTORE write "$key" "$newval" ; then
	mkdir -p $(dirname "$cache")
	echo -n "$newval" > "$cache"
	XENSTORE_UPDATED=1
	return 0
    fi
    return 1
}

# If we detect a domain change then delete our cache and force a refresh
domid=$(/usr/local/bin/xenstore-read "domid")
cache=/var/cache/xenstore/unique-domain-id
newval=$(/usr/local/bin/xenstore-read "/local/domain/${domid}/unique-domain-id")
if [ -e $cache ]; then
    oldval=$(cat "$cache")
    if [ "$oldval" != "$newval" ]; then
	# domain changed
	rm -rf /var/cache/xenstore
    fi
fi
mkdir -p $(dirname "$cache")
echo -n "$newval" > "$cache"

xenstore_rm_cached() {
    key="$1"
    cache=/var/cache/xenstore/$key
    if [ ! -e $cache ] ; then
	return 1
    fi
    # try to write and update cache if successfull
    if $XENSTORE rm "$key" ; then
	rm -rf "$cache"
	XENSTORE_UPDATED=1
	return 0
    fi
    return 1
}

xenstore_list_interfaces_cached() {
    topdir=/var/cache/xenstore/attr
    if [ -d $topdir ] ; then
	cd $topdir 
	for dir in * ; do 
	    [ -f $dir/ip ] && echo $dir
	done
    fi
}

if [ $MEMORY_MODE -eq 1 ] ; then
    # Update the memory information
    /usr/sbin/escribe-meminfo.sh > /procfalse/meminfo
    eval $(cat /procfalse/meminfo | \
	sed -n -e 's/MemTotal\: *\([0-9]*\)[^$]*/memtotal=\1/gp;' \
        -e 's/MemFree\: *\([0-9]*\)[^$]*/memfree=\1/gp;')
    
    xenstore_write_cached "data/meminfo_total" "${memtotal}"
    xenstore_write_cached "data/meminfo_free" "${memfree}"
fi

/usr/sbin/escribe-ip-if.sh > /procfalse/fichero-ip-if

while read linea
do
  if=$(echo $linea | cut -d '|' -f1 | sed 's/ //g')
  inet=$(echo $linea | cut -d '|' -f2 | sed 's/ //g')
  xenstore_write_cached "attr/${if}/ip" "${inet}" 
done < /procfalse/fichero-ip-if

# remove any interfaces that have been unplugged or downed
for at in $(xenstore_list_interfaces_cached) ; do
	borrar=1
	while read linea
	do
	  if=$(echo $linea | cut -d '|' -f1 | sed 's/ //g')
	  [ "${if}" = "${at}" ] && borrar=0 && break
	done < /procfalse/fichero-ip-if
	
	if [ "$borrar" -gt "0" ] ; then
	xenstore_rm_cached "attr/${at}"
	fi
 done

# distro
if [ -f ${XE_LINUX_DISTRIBUTION_CACHE} ] ; then
    . ${XE_LINUX_DISTRIBUTION_CACHE}
    for key in os_name os_majorver os_minorver os_uname os_distro ; do
	new=$(eval echo \${${key}})
	[ -n "${new}" ] || continue
	xenstore_write_cached "data/${key}" "${new}"
    done
fi

# whether I support ballooning or not
xenstore_write_cached "control/feature-balloon" "1"

# build time addons
xenstore_write_cached "attr/PVAddons/MajorVersion" "1"
xenstore_write_cached "attr/PVAddons/MinorVersion" "1"
xenstore_write_cached "attr/PVAddons/MicroVersion" "0" 
xenstore_write_cached "attr/PVAddons/BuildVersion" "47383"
xenstore_write_cached "attr/PVAddons/Installed" "1" 

# update xenstore if necc
if [ $XENSTORE_UPDATED -eq 1 ] ; then
    xenstore_write_cached "data/updated" "$(date)"
fi