#! /bin/bash -e

echo "Validating Task"
python /home/worker/bin/validate_task.py

echo "Retrieving device"
res=`curl --request POST -H "Content-Type: application/json" -d "$DEVICE_CAPABILITIES" http://$CLOUD_HOST/device`
error=`echo $res | jq .error`

if [ "$error" != "null" ]; then
    echo $error
    exit -1
fi

status=`echo $res | jq .session`

if [ "$status" == "null" ]; then
    echo "Session could not be created with a device."
    exit -1
fi

export SESSION_ID=`echo $res | jq .session.id`
export SERIAL_ID=`echo $res | jq -r .proxies.adb.serialId`
export ADB_HOST=`echo $res | jq .proxies.adb.forwardHost`
export ADB_PORT=`echo $res | jq .proxies.adb.port`
export MARIONETTE_HOST=`echo $res | jq .proxies.marionette.forwardHost`
export MARIONETTE_PORT=`echo $res | jq .proxies.marionette.port`
export PROXY_HOST=`echo $res | jq -r .proxyHost`
echo "Retrieved device.  Session: $SESSION_ID"

curl -o /home/worker/data/device.json -s -H "Accept: application/json" http://$CLOUD_HOST/device/properties

buildbot_step 'Clone gaia' tc-vcs checkout /home/worker/gaia/source $GAIA_BASE_REPOSITORY $GAIA_HEAD_REPOSITORY $GAIA_REV $GAIA_REF

cd gaia/source/tests/python/gaia-ui-tests/
python setup.py develop
pip install -Ur gaiatest/tests/requirements.txt
cd /home/worker/

buildbot_step 'Running tests' eval $@

echo "Releasing device."
curl --request POST http://$CLOUD_HOST/device/release
