#!/bin/sh

# secure_imap --- secure IMAP connections with pine

# some specific settings
IMAP_SERVER=mailbox.hrz.tu-chemnitz.de
IMAP_PORT=993
MAILER='pine -P /uni/global/packages/pine-4.0/lib/pine.conf'
PS='ps auxww'

# try to find a free tcp port
FREE_PORT=`free_tcp_port`

# start Stunnel in client mode to create a secure SSL/TLS channel to the IMAP
# server
stunnel -c -d $FREE_PORT -r $IMAP_SERVER:$IMAP_PORT

# backup pine's original config file (just in case)
cp $HOME/.pinerc $HOME/.pinerc.backup

# modify Pine's config file ($HOME/.pinerc) to use the SSH channel 
sed -e "s+^inbox-path=.*+inbox-path={localhost:$FREE_PORT}+" < $HOME/.pinerc > $HOME/.pinerc.tls

# move awk's output to the right place
mv $HOME/.pinerc.tls $HOME/.pinerc
  
#start the mailer
$MAILER

# try to kill stunnel
procs=`$PS | grep "stunnel.*$IMAP_SERVER:$IMAP_PORT" | fgrep -v grep | awk '{ print $2 }'`
kill $procs
