#!/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

export PATH=/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/sbin
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
}

xe_ip_if() {
interfaces=$(/sbin/ifconfig -u | grep ': flags=' | grep xn | cut -d ':' -f1)
for if in $interfaces ; do
	echo $(echo $if | sed 's/xn/eth/g') "|" $(/sbin/ifconfig $if | grep 'inet ' | cut -d ' ' -f2)
done
}

if [ $MEMORY_MODE -eq 1 ] ; then
	# calc memory... used http://www.cyberciti.biz/files/scripts/freebsd-memory.pl.txt as guide
	pagesize=$(sysctl hw.pagesize | cut -d ':' -f2)
	memtotal=$(let "$(sysctl hw.physmem | cut -d ':' -f2) / 1024")
	meminactive=$(let "$(sysctl vm.stats.vm.v_inactive_count | cut -d ':' -f2) * $pagesize / 1024")
	memcache=$(let "$(sysctl vm.stats.vm.v_cache_count | cut -d ':' -f2) * $pagesize / 1024")
	memfree=$(let "$(sysctl vm.stats.vm.v_free_count | cut -d ':' -f2) * $pagesize / 1024")
	memavail=$(let "$meminactive + $memcache + $memfree")

	# we're using memavail as "free" for now
	xenstore_write_cached "data/meminfo_total" "$memtotal"
	xenstore_write_cached "data/meminfo_free" "$memavail"
fi

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

# remove any interfaces that have been unplugged or downed
for at in $(xenstore_list_interfaces_cached) ; do
	link=1
	xn=$(echo $at | sed 's/eth/xn/')
	iface=$(/sbin/ifconfig $xn | grep UP | cut -d ':' -f1)
	[ "${iface}" = "${xn}" ] && link=0
	
	if [ "$link" -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" "6"
xenstore_write_cached "attr/PVAddons/MinorVersion" "2"
xenstore_write_cached "attr/PVAddons/MicroVersion" "0" 
xenstore_write_cached "attr/PVAddons/BuildVersion" "76888"
xenstore_write_cached "attr/PVAddons/Installed" "1" 

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