#!/bin/bash
set -e

echo "Waiting for PostgreSQL to start..."
until pg_isready -U admin -h localhost; do
  sleep 2
done

echo "PostgreSQL is ready. Creating databases and users..."

# Create databases
for db in matrix_synapse matrix_mas matrix_signal matrix_whatsapp paperless immich shlink spliit audiomuse; do
  echo "Creating database: $db"
  createdb -U admin "$db"
done

# Create users and set permissions
for db in matrix_synapse matrix_mas matrix_signal matrix_whatsapp paperless immich shlink spliit audiomuse; do
  user="${db}_user"
  password_var="${user^^}_PASSWORD"
  password=${!password_var}
  
  if [ -z "$password" ]; then
    echo "Warning: Password for $user not set. Using default."
    password="default_password"
  fi
  
  echo "Creating user: $user"
  psql -U admin -c "CREATE USER $user WITH PASSWORD '$password';"
  psql -U admin -c "GRANT ALL PRIVILEGES ON DATABASE $db TO $user;"
  psql -U admin -c "ALTER DATABASE $db OWNER TO $user;"
done

# Enable extensions in immich database
echo "Enabling extensions in immich database..."
psql -U admin -d immich -c "CREATE EXTENSION IF NOT EXISTS vector;"
psql -U admin -d immich -c "CREATE EXTENSION IF NOT EXISTS pg_vectorscale;"

echo "PostgreSQL initialization complete!"
