#!/bin/bash 
#           -xv
# OProfile accelerator setup script for hybrid application use.
#
# -----------------------------------------------------------------------------
# Licensed Materials - Property of IBM
# 5724-S84
# (C) Copyright IBM Corp. 2007,2007 All Rights Reserved
# US Government Users Restricted Rights - Use, duplication or
# disclosure restricted by GSA ADP Schedule Contract with
# IBM Corp.
#

if [ `uname -m` != "ppc64" ] ; then
	echo "This program must run on a Cell Blade of a hybrid system."
	exit 1
fi

echo "oprofilea starting ..."

source $HYBRID_PERF_TOOLS_DIR/perfToolAcceleratorSetup

echo "oprofilea after setup ... "

# Global Declarations
opcontrol=`which opcontrol`

# Sanity Checks
if test ! -x  "$opcontrol" ;  then
  printf "$SCRIPT:$LINENO: the command $opcontrol is not available - aborting.\n"
  exit 192
fi

TEMP=`getopt -o h --long help -n '$SCRIPT' -- "$@"`

if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

eval set -- "$TEMP"

while true ; do
        case "$1" in
                -h|--help)
                        printf "%s\n" "usage: this script is meant to be invoked from the oprofileh script via DACS"
                        exit 0 ;;
                --)
                        shift ; break ;;
                *)
                        echo "Internal error" ; exit 1 ;;
        esac
done

echo "Remaining arguments:"
for arg do
        echo '-->'"\`$arg'"
        PROGRAM="$PROGRAM $arg"
done

if [ "$CELL_EVENT" = "" ] ;	then echo "CELL_EVENT environment var is required" ; exit 1 ; fi
if [ "$RUNID" = "" ] ;		then echo "RUNID environment var is required" ; exit 1 ; fi

if [ "$SCRIPT_DEBUG" ] ; then
	echo "oprofilea environment:"
	echo "PROGRAM      = $PROGRAM"
	echo "CELL_VM      = $CELL_VM"
	echo "CELL_EVENT   = $CELL_EVENT"
	echo "RUNID        = $RUNID"
	echo "CELL_OPTIONS = $CELL_OPTIONS"
fi

# Open up the permissions on the data directory so that 'nobody' can write to it.
# (sudo runs as root but NFS ignores root and does the file I/O as 'nobody'.)
chmod 777 $PERF_DATA_DIR
if [ "$CELL_EVENT" != "none" ] ; then
	CELL_DATA_DIR=$PERF_DATA_DIR/oprofile/$RUNID/cbe/`hostname`
	echo "OProfile CBE data directory: $CELL_DATA_DIR"
	sudo opcontrol --init
	sudo opcontrol --reset --session-dir=$CELL_DATA_DIR
	sudo opcontrol $CELL_VM $CELL_EVENT --session-dir=$CELL_DATA_DIR 
	sudo opcontrol --start $CELL_OPTIONS
fi
echo "Calling CBE app..."
$PROGRAM
echo "Exited CBE app..."
if [ "$CELL_EVENT" != "none" ] ; then
	sudo opcontrol --stop --session-dir=$CELL_DATA_DIR
	sudo opcontrol --dump
	sudo opcontrol --deinit
fi

echo "End of oprofilea"

exit 
