#!/bin/bash
# Clean up LD_PRELOAD
export LD_PRELOAD=""

# Check usage
if [ "$#" -lt "2" ]
then
	echo "Usage: `basename \"$0\"` /path/to/executable /path/to/crashdump"
	exit;
fi

# inputs
EXE=$( readlink -f "$1" )
DMP=$( readlink -f "$2" )

# variables
EXENAME=$(basename "${EXE}")
EXEDIR=$(dirname "${EXE}")
DMPNAME=$(basename "${DMP}")
DMPDIR=$(dirname "${DMP}")
FERALHOME="/home/$USER/.local/share/feral-interactive"
CRASHDIR="${DMPDIR}"
DATETIME="$(date +%Y-%m-%d-%H-%M-%S)"
WALKED="${CRASHDIR}/${DATETIME}_crash.log"
WALKLOG="${CRASHDIR}/${DATETIME}_walklog.log"

# Default to local symbols dir
# This is legacy and won't exist anymore ( but for simplicity symbols can be placed here )
SYMDIR="${EXEDIR}/symbols"
if [[ ! -d $SYMDIR ]]; then
	# try and escape out into the main build directory
	SYMDIR="${EXEDIR}/../../../breakpad_symbols"
	if [[ ! -d $SYMDIR ]]; then
		# Otherwise default to inside preferences
		SYMDIR="${FERALHOME}/symbols"
	fi
fi

# try and walk the symbols first
echo "CRASH_REPORTER: Attempting automatic walking the symbols from ${DMPNAME} with ${SYMDIR}"
"${EXEDIR}/minidump_stackwalk" "${DMP}" "${SYMDIR}" 2> "${WALKLOG}" > "${WALKED}"
RESULT=$?

# Check the result for failure
if [[ ! $RESULT == 0 ]]; then
	echo "CRASH_REPORTER: ERROR - automatic walk has failed - ${WALKLOG}"

	# Possibly crash symboliser dirs
	CRASH_SYMBOLISER_DIR="${HOME}/FeralCrashLogger"
	CRASH_SYMBOLISER="${CRASH_SYMBOLISER_DIR}/SymboliseLinuxCrashDump.pl"

	# Output instructions (needs interactive & sudo)
	echo "CRASH_REPORTER: See https://confluence.feral.co.uk/display/DEV/Crash+Handling"
	echo "CRASH_REPORTER: Please download FeralCrashLogger and run:"
	echo "CRASH_REPORTER: $ ${CRASH_SYMBOLISER} ${DMP}"

	exit 0
else
	# check the output log for an error on reading the symbols
	HASH=`grep "INFO: Couldn't load symbols for: ${EXENAME}" "${WALKLOG}" | sed 's/.*|//'`

	# if we find a failure to load, output the way to generate these symbols
	if [[ ! -z "$HASH" ]]; then
		echo "CRASH_REPORTER: Crashwalk failed due to lack of symbols"
		echo "CRASH_REPORTER: See https://confluence.feral.co.uk/display/DEV/Crash+Handling"
		echo "CRASH_REPORTER: manually generate symbols with"
		echo "$ mkdir -p \"${SYMDIR}/${EXENAME}/${HASH}\" && \"$EXEDIR/dump_syms\" \"${EXE}\" > \"${SYMDIR}/${EXENAME}/${HASH}/${EXENAME}.sym\""
		echo "CRASH_REPORTER: symbolise this crash with"
		echo "$ \"$( readlink -f "$0" )\" \"$EXE\" \"$DMP\""

		# remove the failed crash
		rm "${WALKED}"
	else
		# otherwise just output the crashwalk
		echo "CRASH_REPORTER: SUCCESS - ${WALKED}"

		# If we have zenity launch a convenience window showing the crash log, but not in BP mode
		if [[ `type -p zenity` ]] && [[ ${SteamTenfoot} -ne 1 ]]; then
			zenity --text-info --width=600 --height=600 --title="CRASH_REPORTER - ${DATETIME}" --filename="${WALKED}"
		fi
	fi
fi
