#!/bin/sh

# Meiga - Lightweight and easy to use web file server for your desktop
#
# Copyright (C) 2009 Igalia, S.L.
#
# Authors:
#
# Igalia, S.L. <info@igalia.com>
# Enrique Ocaña González <eocanha@igalia.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

# Auxiliar task
# Expects the following environment variables:
# SERVER_IP, EXTERNAL_PORT, INTERNAL_IP, INTERNAL_PORT, PIDFILE
# Supports the following optional environment variables:
# SSH_USER, SSH_PASSWORD, SSH_PORT

# We can't rely on the PATH being properly set if this tool is executed
# from a DBUS daemon
export PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:$PATH"

unset SSH_AGENT_PID
unset SSH_AUTH_SOCK
unset USERSTRING
unset PORTSTRING
export SSH_ASKPASS='meiga-askpass'

if [ -n "$SSH_USER" ]
then USERSTRING="$SSH_USER@"
fi

if [ -n "$SSH_PORT" ]
then PORTSTRING="-p $SSH_PORT"
fi

TOKEN=`date +%N`
( ssh -T -f -N -g \
 -o ConnectTimeout=5 -o ConnectionAttempts=1 \
 -o NumberOfPasswordPrompts=1 \
 -R "$EXTERNAL_PORT:$INTERNAL_IP:$INTERNAL_PORT" \
 "$USERSTRING$SERVER_IP" $PORTSTRING $TOKEN ) &
sleep 7;
ps axu |
grep $TOKEN |
grep -v grep |
{
 read _ X _
 echo $X
} > $PIDFILE

