#!/bin/sh
set -e

echo "Starting iMail container initialization..."

# Ensure storage directories exist
mkdir -p /var/www/html/storage/framework/cache/data
mkdir -p /var/www/html/storage/framework/sessions
mkdir -p /var/www/html/storage/framework/views
mkdir -p /var/www/html/storage/logs
mkdir -p /var/www/html/storage/app/public
mkdir -p /var/www/html/bootstrap/cache

# Fix permissions
chown -R www-data:www-data /var/www/html/storage
chown -R www-data:www-data /var/www/html/bootstrap/cache

# Cache configuration, routes, views, events
echo "Caching configuration and routes..."
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache

# Create storage symlink
php artisan storage:link --force

# Run migrations (non-fatal — don't crash the container if a migration fails)
echo "Running migrations..."
php artisan migrate --force || echo "WARNING: Migrations failed. The container will continue starting. Please check the migration error above and fix manually."

echo "Initialization complete. Starting Supervisord..."
# Execute supervisord in the foreground
exec /usr/bin/supervisord -c /etc/supervisor/conf.d/supervisord.conf
