#! /bin/bash

COREPATH="$HOME/corefiles/"

if [[ ! -d "$COREPATH" ]]; then
  # check if ~/corefiles exists and is not empty
  echo "$COREPATH missing, creating it now"
  mkdir -p $COREPATH
  exit 1
elif (( "$(ls -t1 -I "*.txt" ~/corefiles/ | wc -l)" == "0" )); then
  # use latest corefile
  # check for at least one file
  # TODO: print setup-guideline if it's missing
  echo "no corefiles found in $COREPATH, check your setup!"
  exit 1
elif (( $# == 0 )); then
  #  use latest corefile
  DUMP=$COREPATH$(ls -t1 -I "*.txt" $COREPATH | head -1)
elif (( $# == 1 )); then
  DUMP=$1
else
  echo "Usage: mikado-backtrace-corefile corefilename"
  exit 1
fi

echo corefile: $DUMP

EXENAME=$(file -Pelf_phnum=10000 $DUMP | sed "s/.*execfn: '\([^']*\).*/\1/")
DUMP_DATE=$(date -I -r $DUMP)
OUT_FILE=$DUMP-${DUMP_DATE}_gdb.txt

echo "Creating backtrace for $EXENAME with coredump $DUMP"
echo 

gdb $EXENAME $DUMP -ex "set logging on" -ex "set pagination off" -ex "info threads" -ex "thread apply all bt" -ex quit ; mv gdb.txt $OUT_FILE

echo 
echo "Backtrace output: $OUT_FILE"

echo "Currently installed version of the package containing \"$EXENAME\""
dpkg -l $(dpkg -S $EXENAME | cut -d: -f1) | grep "^ii"

echo "Done."
