#!/bin/bash
set -euo pipefail

CONFIG_FILE="config.yaml"
DEFAULT_PASSWORD="changeme"

# Check and install yq if missing
install_tool_if_missing() {
  local tool=$1
  if ! command -v "$tool" &> /dev/null; then
    echo "$tool is not installed."
    if [[ "$(uname)" == "Darwin" ]]; then
      if command -v brew &> /dev/null; then
        echo "Installing $tool using Homebrew..."
        brew install "$tool"
      else
        echo "Homebrew is not installed. Please install Homebrew first: https://brew.sh/"
        exit 1
      fi
    else
      echo "Automatic installation of $tool is only supported on macOS with Homebrew."
      exit 1
    fi
  fi
}

install_tool_if_missing yq
install_tool_if_missing jq
install_tool_if_missing curl

ES_ENDPOINT=$(yq e '.elasticsearch.endpoint' "$CONFIG_FILE")
ES_USER=$(yq e '.elasticsearch.user' "$CONFIG_FILE")
ES_PASS=$(yq e '.elasticsearch.password' "$CONFIG_FILE")

roles=$(yq e '.roles | keys | .[]' "$CONFIG_FILE")

for role in $roles; do
  echo "----------------------------"
  echo "Creating/updating role: $role"

  # Extract role config as JSON
  role_json=$(yq e -o=json ".roles.\"$role\"" "$CONFIG_FILE")

  # Add description if present
  description=$(yq e ".roles.\"$role\".description" "$CONFIG_FILE")
  if [[ "$description" != "null" && "$description" != "" ]]; then
    role_json=$(echo "$role_json" | jq --arg desc "$description" '. + {description: $desc}')
  fi

  # Create or update role
  role_response=$(curl -s -w "%{http_code}" -o /tmp/role_response.json -X PUT "$ES_ENDPOINT/_security/role/$role" \
    -u "$ES_USER:$ES_PASS" \
    -H "Content-Type: application/json" \
    -d "$role_json")

  if [[ "$role_response" == "200" || "$role_response" == "201" ]]; then
    echo "Role '$role' created/updated successfully."
  else
    echo "Error creating/updating role '$role'. HTTP status: $role_response"
    echo "Response:"
    cat /tmp/role_response.json
    exit 1
  fi

  # Prepare user payload JSON
  user_json=$(jq -n --arg pw "$DEFAULT_PASSWORD" --arg role "$role" '{
    password: $pw,
    roles: [$role],
    full_name: ($role | ascii_upcase),
    email: ($role + "@example.com")
  }')

  echo "Creating/updating user: $role"

  # Create or update user
  user_response=$(curl -s -w "%{http_code}" -o /tmp/user_response.json -X PUT "$ES_ENDPOINT/_security/user/$role" \
    -u "$ES_USER:$ES_PASS" \
    -H "Content-Type: application/json" \
    -d "$user_json")

  if [[ "$user_response" == "200" || "$user_response" == "201" ]]; then
    echo "User '$role' created/updated successfully."
  else
    echo "Error creating/updating user '$role'. HTTP status: $user_response"
    echo "Response:"
    cat /tmp/user_response.json
    exit 1
  fi
done

echo "All roles and users processed successfully."
