USER=
FORUM_PASS=
WC3C_PASS=

#Old version:
#
#function login
#{
## Log in and fetch token
#curl -sc entcook https://entgaming.net/ > /dev/null
#sid=$(grep -Eo 'sid\s[0-9a-zA-Z]+' entcook | grep -Eo '[0-9a-zA-Z]+$')
#curl -sib entcook -c entcook https://entgaming.net/forum/ucp.php?mode=login -F username=$USER -F password=$FORUM_PASS -F login=Login -F sid=$sid > /dev/null
#curl -siLb entcook -c entcook https://entgaming.net/link/gotohost.php > /dev/null
#toke=$(grep -Eo 'token\s[0-9a-zA-Z]+' entcook | grep -Eo '[0-9a-zA-Z]+$')
## checktoke
#curl https://host.entgaming.net/checktoken -d token=$toke
#}
#
#function mapsearch
#{
#login
## Get map codes
#curl https://host.entgaming.net/search -d "token=$toke&filter=$@" | jq '.maps[]'
## This is P220904E's code, probably never changes
##jsnj8
## Abyss 1.8.7: ccyms
## Terrania 113: ua4uy
#}
#
#function host
#{
#login
##locs: atlanta, ny, europe, amsterdam
##means: montreal, new york, france, amsterdam
#while [ -z "$a" ]; do
#b=$(curl -s https://host.entgaming.net/host -d "token=$toke&owner=$USER&mapcode=${2:-jsnj8}&location=${1:-ny}&loadingame=no")
#a=$(jq '.error == "you already have a game hosted (in lobby)" // empty' <<< "$b")
#backoff=$(jq '.error == "you already have a game in the hosting queue, it will be hosted soon" // empty' <<< "$b")
#echo $b
#sleep 1
#[ -n "$backoff" ] && sleep 2
#done
#}
#
#[ -z "$1" ] && host
#$@ || host $@

function login
{
	echo logging in...
	sid=`curl -sc entcook -b entcook https://entgaming.net/forum/ucp.php?mode=login | grep -om1 'sid=[^"]*' | cut -d= -f2`
	curl -sc entcook -b entcook https://entgaming.net/forum/ucp.php?mode=login -F username=$USER -F password=$FORUM_PASS -F sid=$sid -F login=Login
	curl -Lsc entcook -b entcook https://entgaming.net/link/gotohost.php > /dev/null
}

while getopts clsb: var; do case $var in
	c) curl localhost:8333/login -d username=$USER -d password=$WC3C_PASS;;
	l) login;;
	s) search=1;;
	b) bot=$OPTARG;;
esac; done
shift $((OPTIND-1))

toke=`grep token entcook | cut -f7`

maps="swat: jsnj8, swat new:snzur, fferpg: ez9nu, terrania: ua4uy, abyss: ccyms, dotd: 4uwp2, eclipse: deb3e, orcs: ota1l"

#locs: atlanta, ny, europe, amsterdam
#means: montreal, new york, france, amsterdam

if [ -n "$search" ]; then
	[ -z "$1" ] && echo $maps && exit
	curl https://host.entgaming.net/search -d filter="$@" -d token=$toke
else
	echo $1
	while [ -z "$roop" ]; do
		res=`curl -s  https://host.entgaming.net/host -d token=$toke -d owner=$USER -d mapcode=${1:-snzur} -d location=${bot:-ny} -d observers=no -d loadingame=yes`
		echo $res
		[ -n "`jq '.error == "invalid token, please refresh" // empty' <<< "$res"`" ] && login && toke=`grep token entcook | cut -f7`
		roop=$(jq '.error == "you already have a game hosted (in lobby)" // empty' <<< "$res")
		backoff=$(jq '.error == "you already have a game in the hosting queue, it will be hosted soon" // empty' <<< "$res")
		sleep 1
		[ -n "$backoff" ] && sleep 2
	done
fi
