From b88a98348b3841f0b702e314631883d46f9f362d Mon Sep 17 00:00:00 2001
From: "NODA, Kai" <nodakai@gmail.com>
Date: Sun, 22 Apr 2012 17:01:02 +0900
Subject: [PATCH] Use /proc/self/exe for "swig -swiglib" on non-Win32
 platforms.

If it wasn't found, then fall back to a fixed string just as before.

Upstream-Status: Submitted
http://sourceforge.net/mailarchive/message.php?msg_id=29179733
---
 Source/Modules/main.cxx | 24 ++++++++++++++++++++++--
 1 file changed, 22 insertions(+), 2 deletions(-)

diff --git a/Source/Modules/main.cxx b/Source/Modules/main.cxx
index 76b4f9d..de0a512 100644
--- a/Source/Modules/main.cxx
+++ b/Source/Modules/main.cxx
@@ -25,6 +25,11 @@
 #include <ctype.h>
 #include <errno.h>
 #include <limits.h>		// for INT_MAX
+#ifndef _WIN32
+#include <cstddef>
+#include <unistd.h>		// for readlink
+#include <sys/stat.h>		// for stat
+#endif
 
 // Global variables
 
@@ -895,9 +900,9 @@ int SWIG_main(int argc, char *argv[], const TargetLanguageModule *tlm) {
 
   // Check for SWIG_LIB environment variable
   if ((c = getenv("SWIG_LIB")) == (char *) 0) {
+    char *p;
 #if defined(_WIN32)
     char buf[MAX_PATH];
-    char *p;
     if (!(GetModuleFileName(0, buf, MAX_PATH) == 0 || (p = strrchr(buf, '\\')) == 0)) {
       *(p + 1) = '\0';
       SwigLib = NewStringf("%sLib", buf); // Native windows installation path
@@ -907,7 +912,22 @@ int SWIG_main(int argc, char *argv[], const TargetLanguageModule *tlm) {
     if (Len(SWIG_LIB_WIN_UNIX) > 0)
       SwigLibWinUnix = NewString(SWIG_LIB_WIN_UNIX); // Unix installation path using a drive letter (for msys/mingw)
 #else
-    SwigLib = NewString(SWIG_LIB);
+    char buf[PATH_MAX];
+    if (0 < ::readlink("/proc/self/exe", buf, sizeof(buf)) &&
+        (p = ::strstr(buf, "/bin/swig"))) {
+        int major, minor, patch;
+        const int ret = ::sscanf(VERSION, "%d.%d.%d", &major, &minor, &patch);
+        if (3 == ret) {
+            const ::ptrdiff_t dir_part_len = p - buf;
+            ::snprintf(p, PATH_MAX - dir_part_len, "/share/swig/%d.%d.%d", major, minor, patch);
+            struct ::stat stat_res;
+            if (0 == ::stat(buf, &stat_res) && S_ISDIR(stat_res.st_mode)) {
+                SwigLib = NewString(buf);
+            }
+        }
+    }
+    if (NULL == SwigLib)
+        SwigLib = NewString(SWIG_LIB);
 #endif
   } else {
     SwigLib = NewString(c);
