#!/bin/bash

# We need bash here, because of the *-loader.sh scripts containing bashisms!

## NAME
##   debugvdr - Runs the VDR debugging binary with the GDB debugger.
##
## SYNOPSIS
##   debugvdr [-r]
## 
## DESCRIPTION
##   debugvdr will start VDR with the GDB debugger with the same command line
##   arguments as the VDR daemon. This means, all installed plugins will be
##   loaded. If VDR is still running, it will be automatically stopped before
##   starting the debugging version.
## 
## OPTIONS
##   -r Start VDR with the GDB Server on port 1000 for remote debugging.
## 
## SEE ALSO
##   vdr(1), gdb(1)
## 
## AUTHOR
##   This manual page was written by Tobias Grimm <tg@e-tobi.net>
## 
### txt2man -s 1 -t DEBUGVDR -v "Start VDR with the GDB debugger"

usage()
{
    local HELPCOMMENTPATTERN="^## "
    cat "$0" | grep "$HELPCOMMENTPATTERN" | sed "s/$HELPCOMMENTPATTERN//"
}


while getopts hr opt
do
    case $opt in
        r)
            GDB_SERVER="yes"
            [ -x $2 ] || GDB_SERVER_PORT="$2"
            ;;
        *)
            usage
            exit
            ;;
    esac
done

PLUGINS=""

. /usr/lib/vdr/config-loader.sh
. /usr/lib/vdr/commands-loader.sh
. /usr/lib/vdr/plugin-loader.sh

getplugins
mergecommands "commands"
mergecommands "reccmds"

VDRCOMMANDLINE="-v $VIDEO_DIR -c $CFG_DIR -L $PLUGIN_DIR  -r $REC_CMD \
  -E $EPG_FILE $PLUGINS $OPTIONS --lirc"

/etc/init.d/vdr stop

if [ "$GDB_SERVER" = "yes" ] ; then
    gdbserver host:"$GDB_SERVER_PORT" /usr/bin/vdr-dbg \
      `echo $VDRCOMMANDLINE | sed s/\"//g`

else
    GDB_COMMANDS_FILE=`mktemp`

    echo "set args $VDRCOMMANDLINE"         >>$GDB_COMMANDS_FILE
    echo "echo -----------------------\n"   >>$GDB_COMMANDS_FILE
    echo "echo ---- VDR-Debugging ----\n"   >>$GDB_COMMANDS_FILE
    echo "echo -----------------------\n\n" >>$GDB_COMMANDS_FILE
    echo "echo type 'run' to start vdr\n\n" >>$GDB_COMMANDS_FILE

    gdb -x $GDB_COMMANDS_FILE /usr/bin/vdr-dbg 
    rm $GDB_COMMANDS_FILE
fi
