#!/bin/sh

# secure_imap --- secure IMAP connections with pine
# 
# - creates a secure SSH channel to an IMAP server in the background, 
#   runs ssh_pause to keep the channel open
# - modifies pine's config file to use this channel
# - starts the mailer "pine"
# - after exiting pine, ssh_pause is killed and the channel is closed

# some specific settings
ID_FILE=$HOME/.ssh/identity.imapserv
IMAP_SERVER=saturn
IMAP_PORT=143
MAILER=pine

# add our key for the IMAP server to ssh-agent
ssh-add $ID_FILE

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

# create a secure SSH channel to the IMAP server in the background and keep 
# it open by running ssh_pause on the server
ssh -f -L $FREE_PORT:$IMAP_SERVER:$IMAP_PORT $IMAP_SERVER \
    ssh_pause imap `hostname` $$

# 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 
awk -f - $HOME/.pinerc > $HOME/.pinerc.ssh << END
/^inbox-path=/ { 
     print "inbox-path={localhost:$FREE_PORT}"
     next 
}
{ print }
END

# move awk's output to the right place
mv $HOME/.pinerc.ssh $HOME/.pinerc

#start the mailer
$MAILER

# kill the instance of ssh_pause created above (thereby closing
# the background channel)
ssh $IMAP_SERVER kill_proc ssh_pause imap `hostname` $$
