#!/bin/sh
# Copyright 2008, Revolution Linux Inc.
#
# $Id$
#
# Authors : Francis Giraldeau <francis.giraldeau@revolutionlinux.com>
#
# This file is part of the MILLE-XTERM project.
#
#               http://www.revolutionlinux.com/mille-xterm/
#               http://www.mille.ca/
#
# This program is covered by the GNU General Public License.
# See the COPYING file in the top-level MILLE-XTERM directory.
#
# -------------------------------------------------------------------------
#
# ltsp-loadbalancer-client contacts the ltsp-loadbalancer-server to get the
# best server to use for the session
# 
# This script uses wget for the http request

usage() {
cat 1>&2 <<EOF
$0 [OPTION]

   Get the best server to use from the load-balancer server. 

  -s, --server   Address of the load-balancer server.
  -p, --port     Port that server runs.  Default is 8008.
  -h, --help     This help.
  
EOF
}

# Source global configuration file
if [ -f /etc/ltsp/loadbalancer-client.conf ]; then
    . /etc/ltsp/loadbalancer-client.conf
fi

#
# Handle command line args
#

ARGS=$(getopt -o s:p:t:h --long server:,port:,help,timeout -n $0 -- "$@")

if [ $? != 0 ]; then
    usage
    exit 1                          # getopt failed
fi

eval set -- "${ARGS}"

while true ; do
    case "$1" in
        -s|--server) SERVER=$2 ; shift 2 ;;
        -p|--port) PORT=$2 ; shift 2 ;;
        -t|--timeout) TIMEOUT=$2 ; shift 2 ;;
        -h|--help) usage ; exit 0 ;;
        --) shift ; break ;;
        *) echo "Internal error!" ; exit 1 ;;
    esac
done

# defaults
PORT=${PORT:-"8008"}
TIMEOUT=${TIMEOUT:-"10"}

test -n "$SERVER" || usage

# do the request

URL="http://$SERVER:$PORT/"

if [ -n "$LBGROUP" ]; then
    URL="$URL?group=$LBGROUP"
fi

# -q : quiet
# -O - : output to stdout
# --timeout : combined timeout
# -t : number of retry
wget -q -O - --timeout=$TIMEOUT -t 1 $URL

if [ $? -ne 0 ]; then
    echo "An error occured while contacting server" 1>&2
    exit 1
fi



