#!/bin/sh
# Copyright 2008, Revolution Linux Inc.
#
# Authors : Francis Giraldeau <francis.giraldeau@revolutionlinux.com>
#
# This program is covered by the GNU General Public License.
#
# -------------------------------------------------------------------------

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

   Get the configuration for the thin-client from ltsp-directory server. 

  -s, --server          Address of the load-balancer server.
  -p, --port            Port that server runs.  (Default: 80)
  -t, --timeout         Connection timeout in seconds. (Default: 10 seconds)
  -l, --log             Log state : boot, login, logout (Default: boot)
  -i, --with-inventory  Send inventory of the thin-client.
  -d, --drop-cache      Force to reload configuration cache.
  -e, --enable-ssl      Use https for query (default: disabled)
  -a                    Export all configuration keys
  -h, --help            This help.
  
EOF
}

# Source global configuration file
if [ -f /etc/ltsp/directory.conf ]; then
    CC_SERVER=`cat /etc/ltsp/directory.conf | awk -F / '{print \$3}'`
fi
if [ -f /etc/ltsp/getltscfg-cluster.conf ]; then
    . /etc/ltsp/getltscfg-cluster.conf
fi

#
# Handle command line args
#

ARGS=$(getopt -o s:p:t:l:idhea --long server:,port:,timeout:,log:,with-inventory,drop-cache,enable-ssl,help -n $0 -- "$@")

if [ $? != 0 ]; then
    echo "Error : getopt failed"
    usage
    exit 1
fi

eval set -- "${ARGS}"

while true ; do
    case "$1" in
        -s|--server) CC_SERVER=$2 ; shift 2 ;;
        -p|--port) PORT=$2 ; shift 2 ;;
        -t|--timeout) TIMEOUT=$2 ; shift 2 ;;
        -l|--log) LOG=$2 ; shift 2 ;;
        -i|--with-inventory) INVENTORY="Y"; shift;;
        -d|--drop-cache) DROP_CACHE="Y"; shift;;
        -e|--enable-ssl) ENABLE_SSL="Y"; shift;;
        -a) EXPORT_CONF="Y"; shift;;
        -h|--help) usage ; exit 0 ;;
        --) shift ; break ;;
        *) echo "Internal error!" ; exit 1 ;;
    esac
done

# defaults
PORT=${PORT:-"80"}
TIMEOUT=${TIMEOUT:-"10"}
INVENTORY=${INVENTORY:-"N"}
DROP_CACHE=${DROP_CACHE:-"N"}
ENABLE_SSL=${ENABLE_SSL:-"N"}
EXPORT_CONF=${EXPORT_CONF:-"N"}
LOG=${LOG:-"boot"}
INTERFACE=$(ip route | grep default | cut -d " " -f5)

if [ -z "$CC_SERVER" ]; then
    echo "Error : --server option is mandatory"
    usage
    exit 1
fi
if [ -z "$LOG" ]; then
    echo "Error : --log option is mandatory"
    usage
    exit 1
fi

if [ "$LOG" = "login" ] && [ -z "$LDM_SERVER" ]; then
    echo "Error : LDM_SERVER env variable is not set, and is mandatory when log=login"
    usage
    exit 1
fi

# Manage cache files
cache_dir="/var/cache/getltscfg-cluster"
cache_lts="$cache_dir/lts.conf"
cache_info="$cache_dir/info.cache"
cache_inventory="$cache_dir/inventory.cache"

if [ -f "cache_info" ];
then
    . $cache_info
fi
if [ -z "$ROOT_SRV" ] || [ -z "$INTERFACE_IP" ] || [ -z "$INTERFACE_MAC" ]; then
    DROP_CACHE=Y
fi
if [ "$DROP_CACHE" = "Y" ]; then
    if [ -d "$cache_dir" ]; then
        rm -Rf $cache_dir
    fi
fi

mkdir -p "$cache_dir"
if [ ! -f "$cache_info" ]; then
    ! touch $cache_info && exit 1
    echo INTERFACE_MAC=$(ifconfig | grep ${INTERFACE} | cut -f11 -d" ") > $cache_info
    echo INTERFACE_IP=$(ifconfig ${INTERFACE} | grep inet | cut -f2 -d":" | cut -f1 -d" ") >> $cache_info
    if [ -f /var/cache/ltsp/ltsp_config ]; then
        . /var/cache/ltsp/ltsp_config
    fi
    echo ROOT_SRV=$NBD_ROOT_HOST >> $cache_info
fi

. $cache_info

if [ -z "$ROOT_SRV" ] || [ -z "$INTERFACE_IP" ] || [ -z "$INTERFACE_MAC" ]; then
    echo Failed to get needed information about the client
    exit 1
fi
if [ ! -f "$cache_inventory" ] && [ "$INVENTORY" = "Y" ]; then
    echo -n "hwlist=" > $cache_inventory
    inventory | sed -e "s/%/%25/g" | sed -e "s/\//%2F/g" | sed -e "s/&/%26/g" | sed -e "s/=/%3D/g" >> $cache_inventory 
fi

# do the request
if [ "$ENABLE_SSL" = "Y" ]; then
    PROTO="https"
    if [ "$PORT" = "80" ]; then
        PORT="443"
    fi
    # Default to insecure but functional SSL
    [ -z "${CHECK_CERTIFICATE}" ] && CHECK_CERTIFICATE="N"
    if [ "${CHECK_CERTIFICATE}" = "N" ]; then
        OPTIONS="--no-check-certificate"
    fi
else
    PROTO="http"
fi

PAGE=${PAGE:-"ltsp-cluster-control/Terminal"}
URL="$PROTO://$CC_SERVER:$PORT/$PAGE"

# -q : quiet
# -O - : output to stdout
# --timeout : combined timeout
# -t : number of retry
OPTIONS="$OPTIONS -q -O $cache_lts -T $TIMEOUT -t 1"

QUERY=""
# Make sure that configuration if fetch only once in the boot process
if [ "$LOG" = "boot" ]; then
    if [ ! -f "$cache_lts" ] || [ "$DROP_CACHE" = "Y" ]
    then
        QUERY="?mac=$INTERFACE_MAC/ip=$INTERFACE_IP/bootservip=$ROOT_SRV/code=1"
        if [ "$INVENTORY" = "Y" ]; then
            QUERY="$QUERY --post-file=$cache_inventory"
        fi
    fi
elif [ "$LOG" = "prompt" ]; then 
    QUERY="?mac=$INTERFACE_MAC/ip=$INTERFACE_IP/appservip=$LDM_SERVER/display=$(echo $DISPLAY | cut -d ":" -f 2)/code=2"
elif [ "$LOG" = "login" ]; then 
    QUERY="?mac=$INTERFACE_MAC/ip=$INTERFACE_IP/appservip=$LDM_SERVER/username=$LDM_USERNAME/display=$(echo $DISPLAY | cut -d ":" -f 2)/code=3"
elif [ "$LOG" = "logout" ]; then
    QUERY="?mac=$INTERFACE_MAC/ip=$INTERFACE_IP/appservip=$LDM_SERVER/username=$LDM_USERNAME/display=$(echo $DISPLAY | cut -d ":" -f 2)/code=4"
elif [ "$LOG" = "refresh" ] || [ "$LOG" = "ldm" ]; then
    QUERY="?mac=$INTERFACE_MAC/ip=$INTERFACE_IP/bootservip=$ROOT_SRV/code=0"
else
    echo "Error : Unknown log operation" 
    usage
    exit 1
fi

if [ -n "$QUERY" ]; then
    logger "wget $OPTIONS $URL/$QUERY"
    wget $OPTIONS $URL/$QUERY

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

if [ "$EXPORT_CONF" = "Y" ]; then 
    getltscfg -a -c $cache_lts
fi
if [ "$LOG" = "ldm" ]; then
    eval $(getltscfg -a -c $cache_lts)
    echo -n $LDM_SERVER
fi
