#! /usr/bin/python
# Debreaper
# copyright (c) 2007 Josselin Mouette
# Licensed under the GPL (v2 only)

import sys, os, time, signal
from utils import *

def help():
  sys.stderr.write("Usage: %s [appname [signum]]\n"%sys.argv[0])
  sys.exit(2)

appname=None
signum=0
if len(sys.argv) > 1:
  if sys.argv[1] in ["-h", "--help"]: help()
  appname=sys.argv[1]
if len(sys.argv) > 2:
  try:
    signum=int(sys.argv[2])
  except ValueError:
    help()

ppid = os.getppid()
if not ppid:
  sys.exit("Can't obtain parent PID")
try:
  path = os.readlink('/proc/%d/exe'%ppid)
except OSError:
  sys.exit("Can't obtain parent executable name")
if not appname:
  appname=os.path.basename(path)

if is_hacker ():
  if attach_debugger (path, ppid):
    sys.exit (0)

if has_tty ():
  from textui import ReaperUI
elif os.fork ():
  # No TTY: continue operation in a child process
  signal.pause ()
  sys.exit (0)
elif has_x11 ():
  from gtkui import ReaperUI
else:
  from nonintui import ReaperUI

from gettext import gettext as _, textdomain
textdomain("debreaper")
ui = ReaperUI (appname, ppid,
	       _("Please wait while collecting information about the crash"))

ui.info_text (_("Extracting application trace"))
gdbout = gdb_output(ppid)

if not has_tty ():
  # Kill the parent PID waiting in its pause()
  # This will release the original crashed application
  os.kill (os.getppid (), signal.SIGUSR1)

ui.info_text(_("Extracting package information"))
from bug_iface import *
status = lookup_package (path)
if not status:
  ui.summary_dialog (_("If you want to help the developers to fix this program, here is the relevant debugging information."), gdbout)
  sys.exit (0)

ui.info_text(_("Extracting dependency information"))
report = generate_report (status[1], status[0], status[2], status[3], path, gdbout)

ui.info_text(_("Sending report"))
if launch_email_client (status[1], signum, report):
  if not has_tty ():
    time.sleep (1)
    ui.finalize ()
else:
  ui.summary_dialog (_('If you want to report this issue, please send the following information by e-mail to "%s".'%"submit@bugs.debian.org"), report)
