#! /bin/bash

until curl -s -X GET "http://localhost:3000" -o /dev/null
do 
  echo "Wait until grafana is ready..."
  sleep 5
done

# Create API key
API_RESPONSE=`curl -s -X POST -H "Content-Type: application/json" -d '{"name":"apikeycurl", "role": "Admin"}' http://admin:admin@localhost:3000/api/auth/keys`
API_KEY=`echo "$API_RESPONSE" | jq -j '.key'`
API_KEY_ID=`echo "$API_RESPONSE" | jq -j '.id'`

# Import alerts
curl -X POST http://localhost:3000/api/alertmanager/grafana/config/api/v1/alerts -H 'Content-Type: application/json' -H 'Accept: application/json' -H "Authorization: Bearer $API_KEY" -d '@alerting.json'
curl -X POST http://localhost:3000/api/folders -H 'Content-Type: application/json' -H 'Accept: application/json' -H "Authorization: Bearer $API_KEY" -d '{"title": "station"}'

# Import station rules
jq -c '.station[]' rules.json | while read rule; do
  echo $rule | curl -X POST http://localhost:3000/api/ruler/grafana/api/v1/rules/station -H 'Content-Type: application/json' -H 'Accept: application/json' -H "Authorization: Bearer $API_KEY" -d '@-'
done

# Cleanup api key
curl -s -X DELETE "http://localhost:3000/api/auth/keys/$API_KEY_ID" -H 'Content-Type: application/json' -H 'Accept: application/json' -H "Authorization: Bearer $API_KEY"