#!/bin/sh

### A wrapper script for the tsocks(8) transparant socksification library.
### Written by Dag Wieers <dag@wieers.com>.
###
### There are 3 modes of operandi:
###
###  * tsocks <program> <args ...>
###
###    This will socksify the current program only.
###    eg.
###         [user@host ~]# tsocks telnet www.foo.org
###
###  * tsocks [on|off]
###
###    This will socksify the current shell (and childs).
###    eg.
###         [user@host ~]# source /usr/bin/tsocks on
###         (user@host ~)# telnet www.foo.org
###         [user@host ~]# source /usr/bin/tsocks off
###
###  * tsocks
###
###    This will create a new socksified shell.
###    eg.
###         [user@host ~]# tsocks
###         (user@host ~)$ telnet www.foo.org
###         (user@host ~)$ exit
###         [user@host ~]#

PRG="$(basename $0)"
LIB="/lib64/libtsocks.so"

function set_socks {
    if [ -z "$LD_PRELOAD" ]; then
        export LD_PRELOAD="$LIB"
    elif ! echo "$LD_PRELOAD" | grep -q "$LIB"; then
        export LD_PRELOAD="$LIB $LD_PRELOAD"
    fi
}

function unset_socks {
    export LD_PRELOAD="$(echo -n "$LD_PRELOAD" | sed "s|$LIB \?||")"
    if [ -z "$LD_PRELOAD" ]; then
        export -n LD_PRELOAD
    fi
}


case "$1" in
    on) set_socks;;
    off)    unset_socks;;
    show|sh)
        if echo "$LD_PRELOAD" | grep -q "$LIB"; then
            echo "$PRG: This shell is socksified."
        else
            echo "$PRG: This shell is NOT socksified."
        fi
        ;;
    -h|-?)  echo "$PRG: Please see tsocks(1) or read comment at top of $0"
        exit 1
        ;;
    '')
        set_socks
#       PS1="$(echo -n "$PS1" | tr \[\] \(\)) " ${SHELL:-/bin/sh};;
        PS1="(\u@\h \W)\$ " ${SHELL:-/bin/sh}
        ;;
    *)  set_socks
        exec "$@"
        ;;
esac
