#!/bin/bash
#
# Startup script to transparantly socksify your system using tsocks.
#
# Written by Dag Wieers <dag@wieers.com>.
#
# chkconfig: - 89 11
# description: Tsocksify is a means to socksify your system transparantly \
#   (using tsocks) on start-up after the network is up and running.
#
# processname: tsocksify
#
# config: /etc/tsocks.conf
# config: /etc/ld.so.preload

source /etc/rc.d/init.d/functions

[ -r /etc/tsocks.conf -a -x /lib64/libtsocks.so ] || disable

RETVAL=0
prog="tsocks"

disable() {
    echo "Warning: your installation is faulty."
    stop
    exit 1
}

start() {
    echo -n $"Socksifying system ($prog): "
    grep "/lib64/libtsocks.so" /etc/ld.so.preload &>/dev/null
    ret=$?
    if [ ! -f /etc/ld.so.preload -o $ret -ne 0 ]; then
        echo "/lib64/libtsocks.so" >>/etc/ld.so.preload
        success $"tsocksify startup"
    elif [ $ret -eq 0 ]; then
        passed $"tsocksify startup"
    else
        failure $"tsocksify startup"
    fi
    RETVAL=$?
    echo
    return $RETVAL
}

stop() {
    echo -n "Unsocksifying system ($prog): "
    grep "/lib64/libtsocks.so" /etc/ld.so.preload &>/dev/null
    if [ $? -eq 0 ]; then
        cat /etc/ld.so.preload | grep -v "/lib64/libtsocks.so" >/etc/ld.so.preload.cache
        mv -f /etc/ld.so.preload.cache /etc/ld.so.preload
        success $"tsocksify shutdown"
    else
        failure $"tsocksify shutdown"
    fi
    RETVAL=$?
    if [ ! -s /etc/ld.so.preload ]; then
        rm -f /etc/ld.so.preload
    fi
    echo
    return $RETVAL
}

restart() {
        stop
        start
}

case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart|reload)
    restart
    ;;
  *)
    echo $"Usage: $0 {start|stop|restart}"
    exit $RETVAL
esac

exit $RETVAL
