#! /bin/bash

# 200 -> 서버 및 realm이 있는 경우
# 404 -> 서버는 있으나 realm이 없는 경우
# 000 -> 서버가 없음
STATUS_CODE="$(curl -s -o /dev/null -w '%{http_code}' http://imxc-keycloak-http/auth/realms/exem)"

if [ $STATUS_CODE -eq 404 ]; then
  TOKEN="$(curl -s -d "client_id=admin-cli" -d "username=admin" -d "password=admin" -d "grant_type=password" http://imxc-keycloak-http/auth/realms/master/protocol/openid-connect/token | jq -r '.access_token')"
  
  echo $TOKEN

  echo "create realm and client"
  # create realm and client
  curl -s -v POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d "@/tmp/init.json" http://imxc-keycloak-http/auth/admin/realms


  echo "create admin and owner"
  # create admin and owner
  curl -s -v POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d '{"firstName":"","lastName":"", "username":"admin","email":"admin@example.com", "enabled":"true","credentials":[{"type":"password","value":"admin","temporary":false}]}' http://imxc-keycloak-http/auth/admin/realms/exem/users
  curl -s -v POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d '{"firstName":"","lastName":"", "username":"owner","email":"owner@example.com", "enabled":"true","credentials":[{"type":"password","value":"admin","temporary":false}]}' http://imxc-keycloak-http/auth/admin/realms/exem/users

  JWT_KEY="$(curl -s -XGET http://imxc-keycloak-http/auth/realms/exem | jq -r '.public_key')"
  export JWT_KEY

  java -Djava.security.egd=file:/dev/./urandom -jar /app.jar
elif [ $STATUS_CODE -eq 200 ]; then
  echo "exist exem relam"

  JWT_KEY="$(curl -s -XGET http://imxc-keycloak-http/auth/realms/exem | jq -r '.public_key')"
  export JWT_KEY

  java -Djava.security.egd=file:/dev/./urandom -jar /app.jar
else
  echo "not found keycloak. check to install keycloak"
fi
