#!/bin/sh
#=========================================================================
# Script to analyze EPOS applications
#
# Auth: Guto
#=========================================================================

#=========================================================================
# CUSTOMIZABLE DEFINITIONS
#=========================================================================
TMP=/tmp
NM="nm -f posix"
DEMANGLE=c++filt
SYSTEM_NAMESPACE=System

#=========================================================================
# VARIABLES
#=========================================================================
status=0
do_exec=eval
do_echo=:
getting_output_file=0
analyzer=eposanl
my_name=`basename $0`
output_file=/dev/stdout

#=========================================================================
# ARGUMENT PARSING
#=========================================================================
for arg in "$@" ; do
    if [ $getting_output_file = 1 ] ; then
	getting_output_file=0
	output_file="$arg"
	continue
    fi
    case "$arg" in 
    -o)
	getting_output_file=1
	;;
    -u)
	nm_flags="$analyze_flags $args"
	;;
    --help)
	echo "This is a script to extract system dependencies from "
	echo "pre-compiled EPOS programs."
	echo
	echo "Options:"
        echo "  -o <FILE> write output to <FILE>"
	echo "  --help    print this help"
	echo
	echo "Examples:"
	echo "   $my_name foo.o"
	echo "   $my_name -o foo.anl foo.o"
	exit 1
	;;
    *)
	if [ -s "$arg" ] ; then
	    ext=`expr "$arg" : '.*\(\..*\)'`
	    if [ "$ext" = ".o" ] ; then
		input_file="$arg"
	    elif [ "$ext" = ".a" ] ; then
		input_file="$arg"
	    else
		echo "Error: input fille must be compiled with -DANALYZE!"
		exit -1
	    fi
	else
	    echo "Error: invalid argument \"$arg\"!"
	    exit -1
	fi
	;;
    esac
done

#=========================================================================
# COMMAND ISSUING
#=========================================================================
#if [ -z $output_file ] ; then
#    output_file="`basename $arg $ext`.anl"
#fi


#if [ -s $output_file ] ; then
#    echo "Error: file \"$output_file\" already exists!"
#    exit -1
#fi

symtab=`$NM $nm_flags $input_file | cut -d" " -f1 | grep -v __vt | $DEMANGLE \
	| grep "$SYSTEM_NAMESPACE" | cut -d":" -f5- | sort`
ints=`echo "$symtab" | cut -d":" -f1 | sort -u`

echo -n "" > $output_file
for int in $ints ; do
    echo $int "{" >> $output_file
    methods=`echo "$symtab" | grep "$int::" | cut -d":" -f3-  \
		| sed s/"$SYSTEM_NAMESPACE.*::"//g \
		| sed s/"~$int"/destructor/g \
		| sed s/"$int"/constructor/g`
    echo "`echo "$methods" | awk '{print "\t"$n";"}'`" >> $output_file
    echo "}" >> $output_file
    echo >> $output_file
done
	
exit $status
