#! /bin/sh /usr/share/dpatch/dpatch-run
## 10_debian.dpatch by Robert S. Edmonds <edmonds@debian.org>
##
## All lines beginning with `## DP:' are a description of the patch.
## DP: debian environment; look for helpers in /usr/lib/c-repl
## DP: use a mktemp'd directory 
## DP: compile DSOs with -fPIC
## DP: don't write a #include when @headers is empty

@DPATCH@
diff -urNad c-repl-0.0.20071223~/c-repl c-repl-0.0.20071223/c-repl
--- c-repl-0.0.20071223~/c-repl	2007-12-22 22:07:55.000000000 -0500
+++ c-repl-0.0.20071223/c-repl	2007-12-22 22:52:09.000000000 -0500
@@ -1,7 +1,9 @@
-#!/usr/bin/ruby
+#!/usr/bin/env ruby
 # c-repl -- a C read-eval-print loop.
 # Copyright (C) 2006 Evan Martin <martine@danga.com>
 
+$:.unshift("/usr/lib/c-repl")
+
 require 'readline'
 require 'gdbmi'
 require 'codesnippet'
@@ -20,7 +22,7 @@
       response_pipe[0].close
       STDIN.reopen(command_pipe[0])
       command_pipe[0].close
-      exec('./child', response_pipe[1].fileno.to_s)
+      exec('/usr/lib/c-repl/child', response_pipe[1].fileno.to_s)
     end
     command_pipe[0].close
     command_pipe[1].sync = true
@@ -59,6 +61,14 @@
 
 class CREPL
   def initialize
+    @tmpdir = `mktemp -d /tmp/c-repl.XXXXXXXXXX`.strip
+    if $?.to_i != 0
+      $stderr.print "unable to create temporary directory"
+      Process.exit!(1)
+    end
+    Dir.chdir(@tmpdir)
+    at_exit { system "rm -rf #{@tmpdir}" }
+
     @debug = false
     @cur_so_id = 1
     @runner = Runner.new
@@ -94,7 +104,7 @@
       writer.close
       STDIN.reopen(reader)
       reader.close
-      cmd = "gcc -xc -g -shared -o #{name}.so"
+      cmd = "gcc -xc -g -fPIC -shared -o #{@tmpdir}/#{name}.so"
       # add in all libraries
       cmd += ' ' + @libraries.map{|l| "-l#{l}"}.join(' ')
       # tell it to read input through stdin
@@ -116,8 +126,10 @@
   # Generate code from snippet, writing it to out.
   def generate_code(name, snippet, out)
     out.puts "#include <stdio.h>"
-    @headers.each do |header|
-      out.puts "#include \"#{header}\""
+    if @headers
+      @headers.each do |header|
+        out.puts "#include \"#{header}\""
+      end
     end
     @externs.each do |extern|
       out.puts "extern #{extern}"
