#!/bin/sh

# OpenConnect passes:
# CSD_HOSTNAME
# CSD_TOKEN


WGET="wget --no-proxy --no-check-certificate"
#WGET="wget --no-check-certificate"

SERVER=https://${CSD_HOSTNAME}

AUTHDATA=~/.openconnect/authdata.txt

# Downloading "manifest" is redundant since server configuration
# is static and checked offline.
# But some server refuses the login credentials if "manifest" is
# not loaded before.

# UPDATE: 2012-02-27
# only "manifest" is not enough anymore.
# now I download:
# - manifest
# - token.xml
# - data.xml
# - run twice scan.xml
# apparently now is working. Let's see in long run...

${WGET} \
  --user-agent="" \
  -nv \
  "${SERVER}/CACHE/sdesktop/hostscan/windows_i386/manifest" \
  -O /dev/null

ticket=$3
ticket=${ticket}
${WGET} \
  --user-agent="" \
  -nv \
  "${SERVER}/+CSCOE+/sdesktop/token.xml?ticket=${ticket}&stub=0" \
  -O /dev/null


${WGET} --user-agent="" ${SERVER}/CACHE/sdesktop/data.xml -nv -O /dev/null


# POST the static CSD reply

${WGET} \
  --user-agent="" \
  --post-file="${AUTHDATA}" \
  --header="Cookie: sdesktop="${CSD_TOKEN} \
  --header="Content-Type: text/xml" \
  -nv \
  "${SERVER}/+CSCOE+/sdesktop/scan.xml?reusebrowser=1" \
  -O /dev/stdout

${WGET} \
  --user-agent="" \
  --post-file="${AUTHDATA}" \
  --header="Cookie: sdesktop="${CSD_TOKEN} \
  --header="Content-Type: text/xml" \
  -q \
  "${SERVER}/+CSCOE+/sdesktop/scan.xml?reusebrowser=1" \
  -O /dev/null


# Now I should check that the result is:
# <?xml version="1.0" encoding="ISO-8859-1"?>
# <hostscan><status>TOKEN_SUCCESS</status></hostscan>
