#!/bin/sh

cd $HOME
if [ -e .irssitunnel.pid ] && pidof `cat .irssitunnel.pid`; then
    echo "tunnel already started, pid: " `cat .irssitunnel.pid`
else    
    if [ -e .irssitunnel.pid ] ; then
	rm -f .irssitunnel.pid
	echo "removing stale lockfile"
    fi
    cmd="ssh -a -f -L 2777:host.domain.net:2777 -L 2778:host.domain.net:2778 -L 2779:host.domain.net:2779 -L 2780:host.domain.net:2780 -L 2781:host.domain.net:2781 -NT host.domain.net"
    
    # can't use & because then we don't get the password prompt fast enough
    $cmd
    # can't rely on $! because ssh backgrounds by itself
    pid=`ps ax | grep "$cmd" | grep -v grep | awk '{print $1}'`
    
    if [ "$pid" -gt 0 ] ; then
	echo $pid > .irssitunnel.pid
    else
	echo "cannot start tunnel, aborting"
	exit 1
    fi
    
fi

irssi --config=.irssi/config.proxy
tunnel=`cat .irssitunnel.pid`
echo "closing tunnel: $tunnel"
kill $tunnel && rm .irssitunnel.pid

