#!/bin/sh

BUILDDIR=/export/spare/pike/home/nilsson/Pike/7.6/build/`uname -s -r -m|sed "s/ /-/g"|tr "[A-Z]" "[a-z]"|tr "/()" "___"`

if test "$BUILDDIR" = BUILDDIR; then
  echo "Run make in the parent directory to generate this script."
  exit 1
fi

for arg
do
  case "$arg" in
    --gdb*)
      gdb="$arg"
      shift
      ;;

    --valgrind*)
      valgrind="${VALGRIND:-valgrind}"
      vgargs=`expr "$arg" : '--valgrind=\(.*\)'`
      shift
      ;;

    --help*)
      cat <<EOF
Runs Pike directly from the build directory. Some arguments are
handled by this script if they occur before any other:

--gdb[=cmd]
  Pike will be loaded inside a gdb session with the remaining
  arguments. If a value is given, e.g. --gdb=run, it will be passed
  as a command to be executed initially by gdb.

--valgrind[=args]
  Pike will be loaded inside the memory leak detector Valgrind. If a
  value is given, e.g. --valgrind="--num-callers=20 -v", it will be
  split and passed as arguments to valgrind.

--help
  Show this message, but doesn't remove --help from the argument
  list.

Note: It's typically not very useful to specify both --gdb and
--valgrind. You probably want to try --valgrind="--gdb-attach=yes"
instead.

EOF
      break
      ;;

    *)
      break
      ;;
  esac
done

if test "x$gdb" != "x"; then
  args="-DPRECOMPILED_SEARCH_MORE '-m$BUILDDIR/master.pike'"
  for arg
  do
    arg=`sed -e s/\'/\'\"\'\"\'/g <<EOF
$arg
EOF`
    args="$args '$arg'"
  done
  echo "set args $args" >> .gdbinit.$$
  echo break debug_fatal >> .gdbinit.$$
  echo break pike_gdb_breakpoint >> .gdbinit.$$
  if test -f .gdbinit; then
    cat .gdbinit >> .gdbinit.$$
    mv .gdbinit .gdbinit.orig
  fi
  mv .gdbinit.$$ .gdbinit
  gdbcmd=`expr "$gdb" : '--gdb=\(.*\)'`
  if test x"$gdbcmd" != x; then
    echo "$gdbcmd" >> .gdbinit
  fi
  $valgrind $vgargs gdb "$BUILDDIR/pike"
  rm .gdbinit
  test -f .gdbinit.orig && mv .gdbinit.orig .gdbinit
else
  exec $valgrind $vgargs "$BUILDDIR/pike" "-DPRECOMPILED_SEARCH_MORE" "-m$BUILDDIR/master.pike" "$@"
fi
