#!/bin/sh
#
# Extract given process SMAPS data from sp-endurance smaps.cap.lzo files.
# This file is part of sp-endurance.
#
# Copyright (C) 2009 by Nokia Corporation
#
# Contact: Eero Tamminen <eero.tamminen@nokia.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License 
# version 2 as published by the Free Software Foundation. 
#
# 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 St, Fifth Floor, Boston, MA
# 02110-1301 USA

usage ()
{
	name=${0##*/}
	echo
	echo "usage:"
	echo "	$name <program name>"
	echo 
	echo "This can be run in the saved endurance data dir to extract"
	echo "SMAPS information for the named process(es)."
	echo
	echo "Example:"
	echo "	$name pulseaudio"
	echo
	echo "ERROR: $1!"
	echo
	exit 1
}

if [ -z "$(which lzop)" ]; then
	usage "'lzop' utility to extract SMAPS .lzo content is missing"
fi

if [ \! -f 101/smaps.cap.lzo ]; then
	usage "Endurance SMAPS files like '101/smaps.cap.lzo' are missing"
fi

prog=$1
if [ -z "$prog" ]; then
	usage "Give a name for program which info should be extracted"
fi

echo "Searching/extracting SMAPS information for '$prog' from..."
for file in */smaps.cap.lzo; do
	# get snapshot/directory name/number
	num=${file%/*}
	num=${num##*/}
	name=$prog-$num.cap
	echo "- $num"
	# uncompress, take only program info and store that
	lzop -c -d $file | awk "
/^==/ {	show=0 }
/Name: $prog/ {	show=1 }
{ if(show) print }" > $name
done

fgrep -q "Name: $prog" $prog-*.cap
if [ $? -ne 0 ]; then
	echo "ERROR: No matches found for program '$prog'!"
	rm $prog-*.cap
else
	echo "Information extracted:"
	ls $prog-*.cap
fi
