#!/bin/bash
set -e

# Initialize Supabase if needed and ensure default admin user exists
# Requires environment variables:
#   SUPABASE_URL – base URL of Supabase instance (e.g., http://192.168.1.132:8000)
#   SUPABASE_SERVICE_ROLE_KEY – service role secret key with admin privileges
#   DEFAULT_USER_EMAIL – email for the default user (default: info@hephex.de)
#   DEFAULT_USER_PASSWORD – password for the default user (default: Kathi2022!)

DEFAULT_EMAIL="${DEFAULT_USER_EMAIL:-info@hephex.de}"
DEFAULT_PASSWORD="${DEFAULT_USER_PASSWORD:-Kathi2022!}"

if [[ -z "$SUPABASE_URL" || -z "$SUPABASE_SERVICE_ROLE_KEY" ]]; then
  echo "Supabase URL or Service Role Key not set – skipping user creation."
  exit 0
fi

# Check if the user already exists
EXISTING=$(curl -s "${SUPABASE_URL}/auth/v1/admin/users?apikey=${SUPABASE_SERVICE_ROLE_KEY}" \
  -H "Authorization: Bearer ${SUPABASE_SERVICE_ROLE_KEY}" \
  -H "Content-Type: application/json" | grep -i "${DEFAULT_EMAIL}")

if [[ -n "$EXISTING" ]]; then
  echo "Default user ${DEFAULT_EMAIL} already exists."
else
  echo "Creating default user ${DEFAULT_EMAIL}..."
  curl -s -X POST "${SUPABASE_URL}/auth/v1/admin/users?apikey=${SUPABASE_SERVICE_ROLE_KEY}" \
    -H "Authorization: Bearer ${SUPABASE_SERVICE_ROLE_KEY}" \
    -H "Content-Type: application/json" \
    -d "{\"email\": \"${DEFAULT_EMAIL}\", \"password\": \"${DEFAULT_PASSWORD}\", \"email_confirmed\": true}" 
  echo "User created."
fi

exec "$@"
