#!/bin/sh
set -e

echo "Waiting for MySQL..."
until php -r "
try {
    new PDO('mysql:host=mysql;dbname=' . getenv('DB_DATABASE'), getenv('DB_USERNAME'), getenv('DB_PASSWORD'));
} catch(Exception \$e) {
    echo \$e->getMessage();
    exit(1);
}
" 2>/dev/null; do
  sleep 1
done
echo "MySQL is ready."

TABLE_COUNT=$(php -r "
try {
    \$pdo = new PDO('mysql:host=mysql;dbname=' . getenv('DB_DATABASE'), getenv('DB_USERNAME'), getenv('DB_PASSWORD'));
    \$stmt = \$pdo->query('SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = \\'' . getenv('DB_DATABASE') . '\\'');
    echo \$stmt->fetchColumn();
} catch(Exception \$e) {
    echo '0';
}
")

if [ "$TABLE_COUNT" = "0" ]; then
    echo "Database is empty. Importing humicpro_aigo.sql..."
    mysql -h mysql --ssl=0 -u "${DB_USERNAME}" -p"${DB_PASSWORD}" "${DB_DATABASE}" < /var/www/html/humicpro_aigo.sql
    echo "Import complete."
fi

echo "Running Laravel setup..."
php artisan storage:link --force
php artisan config:cache
php artisan route:cache
php artisan view:cache

echo "Starting PHP-FPM..."
exec php-fpm
