#!/bin/sh

# This software is distributed with a BSD License.
# Copyright (C) 2007 TAKANO Yuji. All rights reserved.
# iPod Touch ssh tunnel tool script. stun.sh Version 1.0.1

SERVER="ssh-server"
USER="username"
SRCPORT="143"
DISTPORT="143"

case $1 in
's' )
    C=`/bin/ps -axwww | /usr/bin/grep MobileMail | /usr/bin/grep -v grep | /usr/bin/wc -l`
    if [ $C -gt 0 ];then
	PID=`/bin/ps -axwww | /usr/bin/grep MobileMail | /usr/bin/grep -v grep | /usr/bin/awk '{print $1}'`
	kill -TERM $PID
	echo "Killing MobileMail Process."
	sleep 2;
    fi
    ssh -l $USER -2 -N -f -L ${SRCPORT}:localhost:${DISTPORT} $SERVER
    echo "IMAP4 ssh tunnel OK."
    ;;
't' )
    C=`/bin/ps -axwww | /usr/bin/grep MobileMail | /usr/bin/grep -v grep | /usr/bin/wc -l`
    if [ $C -gt 0 ];then
	PID=`/bin/ps -axwww | /usr/bin/grep MobileMail | /usr/bin/grep -v grep | /usr/bin/awk '{print $1}'`
	kill -TERM $PID
	echo "Killing MobileMail Process."
	sleep 2;
    fi
    PID=`/bin/ps -axwww | /usr/bin/grep ssh | /usr/bin/grep localhost | /usr/bin/grep -v grep | /usr/bin/awk '{print $1}'`
    kill -TERM $PID
    echo "IMAP4 ssh tunnel deleteted."
    ;;
'c' )
    C=`/bin/ps -axwww | /usr/bin/grep ssh | /usr/bin/grep localhost | /usr/bin/grep -v grep | /usr/bin/wc -l`
    if [ $C -gt 0 ];then
	PID=`/bin/ps -axwww | /usr/bin/grep ssh | /usr/bin/grep localhost | /usr/bin/awk '{print $1}'`
	echo "SSH Tunnel PID = $PID"
    fi
    C=`/bin/ps -axwww | /usr/bin/grep MobileMail | /usr/bin/grep -v grep | /usr/bin/wc -l`
    if [ $C -gt 0 ];then
	PID=`/bin/ps -axwww | /usr/bin/grep MobileMail | /usr/bin/grep -v grep | /usr/bin/awk '{print $1}'`
	echo "MobileMail PID = $PID"
    fi
    ;;
* )
    echo "usage: stun.sh { s(start) | t(stop) | c(check) }"
    ;;
esac

echo

