#!/usr/bin/env bash

main() {
  # Check which node is currently serving the dashboard
  DASHBOARD_URL=$(ceph mgr services | jq -r '.dashboard')

  # Get the IP addresses of the current instance
  INSTANCE_IPS=$(hostname -I)

  # Check if any of the host IPs match the instance IPs
  IP_MATCH_FOUND=false
  for INSTANCE_IP in ${INSTANCE_IPS[@]}; do
    if [[ "${DASHBOARD_URL}" =~ "${INSTANCE_IP}" ]]; then
        IP_MATCH_FOUND=true
        break
    fi
  done

  CURL_OPTS=()
  CURL_OPTS+=("-f")
  CURL_OPTS+=("-k")
  CURL_OPTS+=("-s")
  CURL_OPTS+=("--max-time 30")

  if [[ "${IP_MATCH_FOUND}" == "true" ]]; then
    # Check if the dashboard response on the requests
    if ! curl ${CURL_OPTS[@]} ${DASHBOARD_URL} > /dev/null; then
      ceph mgr module disable dashboard
      sleep 10
      ceph mgr module enable dashboard
    fi
  fi
}

main "$@"
