#!/bin/bash

declare -A GET_PARAMS

parse_GET_params() {
  local q p k v

  if [[ ! "${QUERY_STRING}" ]]; then
    return
  fi

  q="${QUERY_STRING}&"

  while [[ ! -z "$q" ]]; do
    p="${q%%&*}"  # get first part of query string
    k="${p%%=*}"  # get the key (variable name) from it
    v="${p#*=}"   # get the value from it
    q="${q#$p&*}" # strip first part from query string

    GET_PARAMS["${k}"]="${v}"
  done
}

echo "Content-Type: text/ascii"
echo "Status: 200 OK"
echo ""

parse_GET_params

if [ ! -z ${GET_PARAMS['username']} -a ! -z ${GET_PARAMS['challenge']} -a ! -z ${GET_PARAMS['nt-response']} ]; then
   #echo ${GET_PARAMS['username']} ${GET_PARAMS['challenge']} ${GET_PARAMS['nt-response']}
   cmd="/usr/bin/ntlm_auth --request-nt-key --username=${GET_PARAMS['username']} --challenge=${GET_PARAMS['challenge']} --nt-response=${GET_PARAMS['nt-response']}"
   #echo $cmd
   echo `$cmd` 

else
   echo "ERROR"
fi  

# /usr/bin/ntlm_auth --request-nt-key --username=wifitest --challenge=89b2cc47d4571192 --nt-response=7413e0e319aa658f2214baadb65c131da88b767ab7771f17
# wget -O - 'http://localhost/cgi/ntlmauth.cgi?username=wifitest&challenge=89b2cc47d4571192&nt-response=7413e0e319aa658f2214baadb65c131da88b767ab7771f17' 