before_script:
  - apt-get update
  - apt-get install -y jq 

variables:
  API_TOKEN:
    description: "Api token"
    value: ""
  TEST_PROJECT_ID:
    description: "Id of test project"
    value: "1"
  TEST_PROJECT_VERSION_ID:
    description: "Id of test project version"    
    value: "2"
  PFLB_URL:
    description: "Pflb deployment url"
    value: "platform.pflb.us"    


stages:         
  - test
  - deploy

load_test:       
  stage: test
  script:
    - |
      CREATE_TEST_RESULT=$(curl -o - --fail-with-body --no-progress-meter -X POST -H "api-token: $API_TOKEN" -H "Content-Type: application/json" -d "{\"testProjectId\":$TEST_PROJECT_ID, \"testProjectVersionId\":$TEST_PROJECT_VERSION_ID}" https://$PFLB_URL/test-srv/api/test )
    - echo $CREATE_TEST_RESULT
    - TEST_ID=$(echo $CREATE_TEST_RESULT | jq '.id')
    - |
      SLA_PROCESSING_STATUS="PROCESSING"
      while [ "$SLA_PROCESSING_STATUS" = "PROCESSING" ] ; do sleep 30; SLA_RESPONSE=$(curl -o - --no-progress-meter -H "api-token: $API_TOKEN" https://$PFLB_URL/test-srv/api/testResult/sla\?testId\=$TEST_ID); echo $SLA_RESPONSE; SLA_PROCESSING_STATUS="$(echo $SLA_RESPONSE | jq -r .testResultSlaState)"; done
    - |
      if [ $SLA_PROCESSING_STATUS = "FINISHED" ]; then SLA_RESULT_STATUS=$(echo $SLA_RESPONSE | jq -r .slaResults.status ); else SLA_RESULT_STATUS="NOT_COUNTED"; fi
    - echo "SLA_RESULT_STATUS=$SLA_RESULT_STATUS" >> build.env
  artifacts:
    reports:
      dotenv: build.env

deploy:
  stage: deploy
  dependencies:
    - load_test    
  script:
    - echo "Load test sla status $SLA_RESULT_STATUS"
    - echo "Add your logic"
