#!/bin/sh

# Copyright (C) CNRS, INRIA, Université Bordeaux 1, Télécom SudParis
# See COPYING in top-level directory.

# usage: eztrace_cc gcc -o foo foo.c -I/usr/include/bar -L/lib/bar -lbar


prefix=/usr
exec_prefix=${prefix}
libdir=${exec_prefix}/lib
includedir=${prefix}/include
bindir=${exec_prefix}/bin

OPARI=/usr/bin/opari2
OPARI_CFLAGS=$(/usr/bin/opari2-config --cflags)
CFLAGS="-I${includedir} $OPARI_CFLAGS"
LDFLAGS="-leztpomp -L${libdir} -Wl,-rpath=${libdir}"

debug=n

usage()
{
cat << EOF
usage: $0 options

OPTIONS:
   -?                               Show this message
   -d				    Enable debug mode
EOF
}

while getopts 'd' OPTION; do
  case $OPTION in
  d)
      echo "[eztrace_cc] Debug mode is ON"
      debug=y
       	;;
  ?)	usage
	exit 2
	;;
  esac
done

# remove the options from the command line
shift $(($OPTIND - 1))

if [ $# -lt 1 ]; then
    usage
    exit 2
fi
cc_cmd=$@

tmpdir=`mktemp -d`
instrumentFile()
{
    param=$1
    new_file_name=$2

# copy the file to tmpdir and instrument it
    param_base=`basename $param`
    param_dir=`dirname $param`
    ${OPARI} --nosrc --omp-task-untied=keep --omp-task-untied=no-warn ${param} $new_file_name

    res_grep=`echo "$cc_cmd" |grep -- "-c" `
    if [ "x$res_grep" != "x" ]; then
	res_grep=`echo "$cc_cmd" |grep -- "-o" `
	if [ "x$res_grep" = "x" ]; then
	    # there is no -o in the compilation line
	    # we need to add -o param.o
	    # otherwise the generated file would be tmp.xxxx.o instead of param.o
	    doto_file=`echo "$param_base" |sed 's/\.[c|f|F]$/\.o/' |sed 's/\.f90$/\.o/'`
	    cc_cmd="$cc_cmd -o $doto_file"
	fi
    fi

    cc_cmd=`echo $cc_cmd -I$param_dir | sed "s@$param\s@$new_file_name @"`
}

cleanup_cmd="rm -rf opari.rc $tmpdir"
for param in $@ ;
do
    case $param in
	*.c )
	    #new_file_name=`mktemp --suffix=.c --tmpdir=$tmpdir 2>/dev/null`
	    new_file_name=$tmpdir/$(basename $param)
#	    if [ $? -ne 0 ]; then
#		new_file_name=`mktemp -p $tmpdir`.c
#	    fi
	    instrumentFile $param $new_file_name
	    ;;
	*.f )
	    new_file_name=`mktemp --suffix=.f --tmpdir=$tmpdir 2>/dev/null`
	    if [ $? -ne 0 ]; then
		new_file_name=`mktemp -p $tmpdir`.f
	    fi
	    instrumentFile $param $new_file_name
	    ;;
	*.F )
	    new_file_name=`mktemp --suffix=.F --tmpdir=$tmpdir 2>/dev/null`
	    if [ $? -ne 0 ]; then
		new_file_name=`mktemp -p $tmpdir`.F
	    fi
	    instrumentFile $param $new_file_name
	    ;;
	*.f90 )
	    new_file_name=`mktemp --suffix=.f90 --tmpdir=$PWD 2>/dev/null`
	    if [ $? -ne 0 ]; then
		new_file_name=`mktemp -p $tmpdir`.f90
	    fi
	    instrumentFile $param $new_file_name
	    ;;
    esac
done

cc_cmd="$cc_cmd $CFLAGS $LDFLAGS"

echo "[eztrace_cc] Running: $cc_cmd"
$cc_cmd
if [ "$debug" != "y" ]; then
    $cleanup_cmd
else
    echo "[eztrace_cc] Temporary files are kept in ${tmpdir}"
fi
