From 7be33e7fd15311382bf807d0f109869ab4d4ec0a Mon Sep 17 00:00:00 2001
From: Michael Raskin <7c6f434c@mail.ru>
Date: Thu, 12 Jun 2008 07:17:37 +0000
Subject: [PATCH] Ported fixSheBang from stdenv-updates to builder-defs.nix,
 tested on Metasploit. No other rebuilds caused.

svn path=/nixpkgs/trunk/; revision=12047
---
 pkgs/tools/security/metasploit/3.1.nix |  4 +---
 pkgs/top-level/builder-defs.nix        | 22 ++++++++++++++++++++++
 2 files changed, 23 insertions(+), 3 deletions(-)

diff --git a/pkgs/tools/security/metasploit/3.1.nix b/pkgs/tools/security/metasploit/3.1.nix
index 8b5e0496d65b..815f0026e8e9 100644
--- a/pkgs/tools/security/metasploit/3.1.nix
+++ b/pkgs/tools/security/metasploit/3.1.nix
@@ -14,15 +14,13 @@ rec {
 
     cp -r * $out/share/msf
 
-    sed -e 's@#!/usr/bin/env ruby@#! ${ruby}/bin/ruby@' -i $out/share/msf/msf*
-
     for i in $out/share/msf/msf*; do
         makeWrapper $i $out/bin/$(basename $i) --prefix RUBYLIB : $out/share/msf/lib
     done
   '') ["minInit" "defEnsureDir" "doUnpack" "addInputs"];
 
   /* doConfigure should be specified separately */
-  phaseNames = ["doInstall"];
+  phaseNames = ["doInstall" (doPatchShebangs "$out/share/msf")];
       
   name = "metasploit-framework" + version;
   meta = {
diff --git a/pkgs/top-level/builder-defs.nix b/pkgs/top-level/builder-defs.nix
index e01699767685..f59f916575a8 100644
--- a/pkgs/top-level/builder-defs.nix
+++ b/pkgs/top-level/builder-defs.nix
@@ -485,4 +485,26 @@ args: with args; with stringsWithDeps; with lib;
      cp -r . $out/share/${shareName}
    '') ["doUnpack" "defEnsureDir"];
 
+   doPatchShebangs = dir: FullDepEntry (''
+     patchShebangFun() {
+     # Rewrite all script interpreter file names (`#! /path') under the
+     # specified  directory tree to paths found in $PATH.  E.g.,
+     # /bin/sh will be rewritten to /nix/store/<hash>-some-bash/bin/sh.
+     # Interpreters that are already in the store are left untouched.
+         header "patching script interpreter paths"
+         local f
+         for f in $(find "${dir}" -type f -perm +0100); do
+             local oldPath=$(sed -ne '1 s,^#![ ]*\([^ ]*\).*$,\1,p' "$f")
+             if test -n "$oldPath" -a "''${oldPath:0:''${#NIX_STORE}}" != "$NIX_STORE"; then
+                 local newPath=$(type -P $(basename $oldPath) || true)
+                 if test -n "$newPath" -a "$newPath" != "$oldPath"; then
+                     echo "$f: interpreter changed from $oldPath to $newPath"
+                     sed -i "1 s,$oldPath,$newPath," "$f"
+                 fi
+             fi
+         done
+     }
+     patchShebangFun;
+   '') ["minInit"];
+
 }) // args