#!/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.

# Forward a port using an ssh server
# 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"

case "$1" in
    "-r")
        export SERVER_IP="$2"
        export EXTERNAL_PORT="$3"
        export INTERNAL_IP="$4"
        export INTERNAL_PORT="$5"
        export PIDFILE="/tmp/fwssh-$EXTERNAL_PORT.pid"
        setsid /bin/sh -c fwssh-task &
        sleep 8
        # Check that the process really exists and exit error code if not
        PIDNUMBER=`cat "$PIDFILE"`
        if [ -z "$PIDNUMBER" ]
        then exit 1
        else
            ps -p $PIDNUMBER > /dev/null
            RESULT=$?
            exit $RESULT;
        fi
        ;;
    "-q")
        export EXTERNAL_PORT="$2"
        export PIDFILE="/tmp/fwssh-$EXTERNAL_PORT.pid"
        if [ -f "$PIDFILE" ]
        then exit 1;
        else exit 0;
        fi
        ;;
    "-d")
        export EXTERNAL_PORT="$2"
        export PIDFILE="/tmp/fwssh-$EXTERNAL_PORT.pid"
        PIDNUMBER=`cat "$PIDFILE"`
        kill $PIDNUMBER
        RESULT=$?
        rm "$PIDFILE"
        exit "$RESULT"
        ;;
    *)
        cat <<EOF
Usage: fwssh OPTION

Options:
-r server_ip external_port internal_ip internal_port
        Add redirection
-q external_port
        Query for redirection
-d external_port
        Delete existing redirection
EOF
esac



