#!/bin/sh
# Wrapper script for use of the tsocks(8) transparent socksification library
#
# There are three forms of usage for this script:
#
# /usr/bin/tsocks program [program arguments...]
#
# This form sets the users LD_PRELOAD environment variable so that tsocks(8) 
# will be loaded to socksify the application then executes the specified 
# program (with the provided arguments). The following simple example might 
# be used to telnet to www.foo.org via a tsocks.conf(5) configured socks server:
#
# /usr/bin/tsocks telnet www.foo.org
#
# The second form allows for tsocks(8) to be switched on and off for a 
# session (that is, it adds and removes tsocks from the LD_PRELOAD environment
# variable). This form must be _sourced_ into the user's existing session
# (and will only work with bourne shell users):
#
# . /usr/bin/tsocks on
# telnet www.foo.org 
# . /usr/bin/tsocks off
# 
# Or
# 
# source /usr/bin/tsocks on
# telnet www.foo.org
# source /usr/bin/tsocks off
#
# The third form creates a new shell with LD_PRELOAD set and is achieved
# simply by running the script with no arguments 
# 
# /usr/bin/tsocks
#
# When finished the user can simply terminate the shell with 'exit'
# 
# This script is originally from the debian tsocks package by 
# Tamas Szerb <toma@rulez.org>

TSOCKSLIB=`ldconfig -p | grep -F /libtsocks. | tail -1 | sed 's/.* //'`
TSOCKSRE='[:[:space:]]*'"$TSOCKSLIB"'[:[:space:]]*'

case "$1" in
  "-c") TSOCKSCONF="$2"; shift; shift;;
esac
TSOCKSCONF="$HOME/.config/libtsocks"
test -r "$TSOCKSCONF" -a -z "$TSOCKS_CONF_FILE" && export TSOCKS_CONF_FILE="$TSOCKSCONF"

case "$1" in
	off)
		export LD_PRELOAD=`echo -n $LD_PRELOAD | sed -E "s@$TSOCKSRE@ @"`
        case "$LD_PRELOAD" in
          ""|" ") unset LD_PRELOAD
        esac
	;;
	show|sh)
		echo "LD_PRELOAD=\"$LD_PRELOAD\""
    ;;
	-h|-?)
      sed -n 's/^# //p' < $0 >&2
    ;;
	*)
		if [ -z "$LD_PRELOAD" ]
			then
				export LD_PRELOAD="$TSOCKSLIB"
			else
				echo $LD_PRELOAD | grep -Fq "$TSOCKSLIB" || \
				export LD_PRELOAD="$TSOCKSLIB $LD_PRELOAD"
		fi
		case "$1" in
          "") ${SHELL:-/bin/sh} ;;
          on) ;;
          *) exec "$@" ;;
        esac
	;;
esac

#EOF
