#!/bin/sh

# Sourced from https://stackoverflow.com/a/29835459/1975049
rreadlink() (
  target=$1 fname= targetDir= CDPATH=
  { \unalias command; \unset -f command; } >/dev/null 2>&1
  [ -n "$ZSH_VERSION" ] && options[POSIX_BUILTINS]=on
  while :; do
      [ -L "$target" ] || [ -e "$target" ] || { command printf '%s\n' "ERROR: '$target' does not exist." >&2; return 1; }
      command cd "$(command dirname -- "$target")"
      fname=$(command basename -- "$target")
      [ "$fname" = '/' ] && fname=''
      if [ -L "$fname" ]; then
        target=$(command ls -l "$fname")
        target=${target#* -> }
        continue
      fi
      break
  done
  targetDir=$(command pwd -P)
  if [ "$fname" = '.' ]; then
    command printf '%s\n' "${targetDir%/}"
  elif  [ "$fname" = '..' ]; then
    command printf '%s\n' "$(command dirname -- "${targetDir}")"
  else
    command printf '%s\n' "${targetDir%/}/$fname"
  fi
)

EXEC=$(rreadlink "$0")
DIR=$(dirname -- "$EXEC")


"$DIR/rakudo-m"  -e '
say "=" x 96;

say qq:to/END/;
This is Rakudo running in valgrind, a tool for debugging and profiling programs.
Running a program in valgrind usually takes *a lot* more time than running it directly,
so please be patient.
Valgrind options can be added with MVM_VALGRIND_OPTS environment variable.
END
say "This Rakudo version is $*RAKU.compiler.version() built on MoarVM version $*VM.version(),";
say "running on $*DISTRO.gist() / $*KERNEL.gist()";

say "-" x 96;
'

VALGRIND="valgrind"
if [ -n "$RAKUDO_VALGRIND" ]; then
    VALGRIND="$RAKUDO_VALGRIND"
fi
"$VALGRIND" ${MVM_VALGRIND_OPTS} "$DIR/rakudo-m"  "$@"
