#! /bin/bash

# Copyright (C) 2010 David Mohr <david@mcbf.net>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# See the file COPYING for the full license text.
#
# midori-dev: Run, update or debug Midori from git.

# Adjust this to where you have your git sources
DEVDIR=~/src/xfce/midori/git

# Location of stdout and stderr from running midori
LOG=~/.midori.out

#-----------------------------------------------------------------------------

BIN=_build/default/midori/midori
BASENAME=`basename $0`

ulimit -c unlimited

cd $DEVDIR

CMD=`echo $BASENAME | sed 's/^midori-//'`
if [ -z $CMD ]; then
  echo "I'm confused, basename $BASENAME is not in the midori-<FOO> format"
  exit 1
fi

if [ $CMD == "dev" ]; then
  # No command was given through a symlink,
  # so check the first parameter instead
  CMD=$1
  shift
fi

case $CMD in
  git)
    exec ./waf build --run "$@" >& $LOG
    ;;
  gdb)
    gdb $BIN core
    ;;
  save)
    NAME=`date '+%Y%m%d-%H%M%S'`
    DESC="$1"
    CAT="$2"
    if [ -z "$1" ]; then
      echo "It is recommended to save a description of the cause of the crash"
      echo "Enter one line now, or press <ENTER> to continue"
      read DESC
    fi
    CRASH=crash/$NAME

    echo "Saving crash info..."
    mkdir -p $CRASH
    echo $DESC > $CRASH/description
    echo "    (gdb will take some time)"
    gdb $BIN core --batch -ex 'thread apply all bt' >& $CRASH/backtrace
    echo "    Backtrace is in $DEVDIR/$CRASH/backtrace."
    cp $BIN $CRASH
    cp core $CRASH
    cp $LOG $CRASH/output

    if [ -n "$CAT" ]; then
      cat $CRASH/backtrace
    fi
    ;;
  pull)
    git pull
    ;;
  *)
    cat << EOM
Usage: Create a symlink midori-<CMD>, or run 'midori-dev <CMD>'
where CMD can be
  git:  run the current git version
  gdb:  open the last core dump in gdb
  save: saves relevant information about the last crash
        so that it can be analyzed later
  pull: pulls the latest updates from the repository
EOM
esac