#! /bin/sh

# Execution profile for Emacs on macOS.
#
# Xcode command-line tools must be installed (use xcode-select
# --install).
#
# Build Emacs with -g.  Install Emacs with 'make install' which copies
# stuff to nextstep/Emacs.app

# Assume we are inside a Git repo.  Chdir to its root.
# Note that .git might be a file when in a git worktree.
while [ ! -e .git ]; do
    cd ..
    if [ `pwd` == "!HOME" ]; then
	echo "$0: Not in a Git repo"
	exit 1
    fi
done

# Check if app was built
if [ ! -d ./nextstep/Emacs.app ]; then
    echo "$0: Cannot find Emacs.app directory"
    exit 1
fi
cd ./nextstep/Emacs.app

# Directory where to store xctrace outout
trace_dir=Xctrace
if [ ! -d "$trace_dir" ]; then
    mkdir "$trace_dir"
fi

# Trace and show the result in Instruments
trace=`xcrun xctrace record --template="Time Profiler" --target-stdout - \
 	      --output "$trace_dir" --launch -- ./Contents/MacOS/Emacs \
	     | grep Output | cut -d : -f 2 | sed -e 's/^ //' -e 's/.$//'`
echo "Trace file is $trace_dir/$trace"
open /Applications/Xcode.app/Contents/Applications/Instruments.app \
     "$trace_dir/$trace"


