#!/bin/ash

DIR=`dirname ${0}`
PID_FILE="/var/run/g-watchdog.pid" # pid file for this script

# if the pid file exists then finish then execution,
# this avoid to have two instances of the same process running at the same time
#[ ! -s ${PID_FILE} ] || exit 0;

# saves the current pid
echo "$$" > ${PID_FILE}

# load the spacific env variables
HOST="develop.getin.mx"

# open a ssh tunnel between the getin server and each sensor
open_tunnel() {
    # open an SSH tunnel for maintain propuses
    HOSTNAME=`cat /proc/sys/kernel/hostname`
    echo ${HOSTNAME}
    PORT=5${HOSTNAME:5}
    echo ${PORT} 
    if [ ${PORT} -eq 5 ]; then
	PORT=50000
    fi

    while true; do
        CONTENT=$(date)
        COMMAND="echo $CONTENT >> tunnel/$HOSTNAME"

        echo "Openning the SSH tunnel ${PORT}:localhost:22 bluemark@${HOST} ..."
	ssh -i /usr/local/allshoppings-cportal/id_rsa_getin -o ExitOnForwardFailure=yes -y -R ${PORT}:localhost:22 bluemark@${HOST} "${COMMAND}; sleep 9000" >> /tmp/tunnel 2>> /tmp/tunnel
	echo "SSH Tunnel closed"
        sleep 1
    done
}

# first called function
main() {
    open_tunnel 
}

main "$@"
