FROM solr:9.9.0

# Switch to root to set up configuration
USER root

# Copy Solr configurations into the image
COPY ./solr/stories /opt/solr-9.9.0/server/solr/configsets/storycove_stories
COPY ./solr/authors /opt/solr-9.9.0/server/solr/configsets/storycove_authors
COPY ./solr/collections /opt/solr-9.9.0/server/solr/configsets/storycove_collections

# Create initialization script using the precreate-core pattern
COPY <<EOF /docker-entrypoint-initdb.d/init-cores.sh
#!/bin/bash
echo "StoryCove: Initializing cores..."

# Repair any cores that are missing core.properties (e.g. after a failed API recreation)
for core in storycove_stories storycove_authors storycove_collections; do
  if [ -d "/var/solr/data/\$core" ] && [ ! -f "/var/solr/data/\$core/core.properties" ]; then
    echo "Repairing broken core: \$core (missing core.properties)"
    rm -rf "/var/solr/data/\$core"
  fi
done

# Create cores on first startup (no-op if they already exist)
precreate-core storycove_stories /opt/solr-9.9.0/server/solr/configsets/storycove_stories
precreate-core storycove_authors /opt/solr-9.9.0/server/solr/configsets/storycove_authors
precreate-core storycove_collections /opt/solr-9.9.0/server/solr/configsets/storycove_collections

# Always sync schema files from the image so deployments pick up schema changes
for core in storycove_stories storycove_authors storycove_collections; do
  src=/opt/solr-9.9.0/server/solr/configsets/\$core/conf/managed-schema
  dst=/var/solr/data/\$core/conf/managed-schema
  if [ -f "\$src" ] && [ -d "/var/solr/data/\$core/conf" ]; then
    cp -f "\$src" "\$dst"
  fi
done

echo "StoryCove: Core initialization complete!"
EOF

# Ensure proper permissions and make script executable
RUN chown -R solr:solr /opt/solr-9.9.0/server/solr/configsets/ && \
    chmod +x /docker-entrypoint-initdb.d/init-cores.sh && \
    chown solr:solr /docker-entrypoint-initdb.d/init-cores.sh

# Switch back to solr user
USER solr

# Use the default Solr entrypoint
CMD ["solr-foreground"]
