#!/bin/sh

. ./$1

cllogin () {
    clientlogin=$(sed  -e 's/$clientname/'$(echo $clientname)'/g' -e 's/$clientkey/'$(echo $clientsecret)'/g' clientlogin.json)
    ret=$(curl -d "$(echo $clientlogin)" "http://$host:$port/api/$domainid" -s --output - )
    conid=$(echo $ret | grep -oP '"connectionid"\s*:\s*"\K[^"]*' )
}

userlogin () {
    userlogin=$(sed  -e 's/$username/'$(echo $username)'/g' -e 's/$userpassword/'$(echo $userpassword)'/g' -e  's/$clientsession/'$(echo $conid)'/g' userlogin.json)
    ret=$(curl -d "$(echo $userlogin)" "http://$host:$port/api/$domainid" -s --output - )
    sessionid=$(echo $ret | grep -oP '"sessionid"\s*:\s*"\K[^"]*' )
}

if [ $2 = 'checkgpo' ]
then
    cllogin
    userlogin
    checkgpo=$(sed  -e 's/$clientsession/'$(echo $conid)'/g' -e 's/$sessionid/'$(echo  $sessionid)'/g' -e  's/$gpoid/'$(echo $3)'/g' checkgpo.json)
    ret=$(curl -d "$(echo $checkgpo)" "http://$host:$port/api/$domainid" -s --output - )
    echo $ret
fi

if [ $2 = 'addconnection' ]
then
    userlogin
    addconnection=$(sed  -e 's/$sessionid/'$(echo  $sessionid)'/g' -e  's/$clientname/'$(echo $3)'/g'  -e  's/$clientsecret/'$(echo $4)'/g' addcon.json)
    ret=$(curl -d "$(echo $addconnection)" "http://$host:$port/api/$domainid" -s --output - )
    echo $ret
fi

if [ $2 = 'remconnection' ]
then
    userlogin
    remconnection=$(sed  -e 's/$sessionid/'$(echo  $sessionid)'/g' -e  's/$clientid/'$(echo $3)'/g' remcon.json)
    ret=$(curl -d "$(echo $remconnection)" "http://$host:$port/api/$domainid" -s --output - )
    echo $ret
fi

if [ $2 = 'sessioninfo' ]
then
    userlogin
    sessioninfo=$(sed  -e 's/$sessionid/'$(echo  $sessionid)'/g' sessioninfo.json)
    ret=$(curl -d "$(echo $sessioninfo)" "http://$host:$port/api/$domainid" -s --output - )
    echo $ret
fi
