#!/bin/sh

set -e

echo "=== Starting Symfony Docker Container ==="

# Configure user permissions to match host user
USER_ID=${USER_ID:-1000}
GROUP_ID=${GROUP_ID:-1000}

# Create a user with the same UID as host user and add to www-data group
if ! id -u hostuser >/dev/null 2>&1; then
    echo "Creating hostuser with UID $USER_ID..."
    useradd -u $USER_ID -g www-data -s /bin/bash hostuser
fi

# Environment variables for PHP
if [ -n "$PHP_MEMORY_LIMIT" ]; then
    echo "memory_limit=${PHP_MEMORY_LIMIT}" > /usr/local/etc/php/conf.d/99-custom.ini
fi

if [ -n "$PHP_MAX_EXECUTION_TIME" ]; then
    echo "max_execution_time=${PHP_MAX_EXECUTION_TIME}" >> /usr/local/etc/php/conf.d/99-custom.ini
fi

if [ -n "$PHP_POST_MAX_SIZE" ]; then
    echo "post_max_size=${PHP_POST_MAX_SIZE}" >> /usr/local/etc/php/conf.d/99-custom.ini
fi

if [ -n "$PHP_UPLOAD_MAX_FILESIZE" ]; then
    echo "upload_max_filesize=${PHP_UPLOAD_MAX_FILESIZE}" >> /usr/local/etc/php/conf.d/99-custom.ini
fi

# Check if a Symfony project is already present
if [ ! -d "/var/www/html/src/" ] && [ ! -d "/var/www/html/public/" ]; then
    echo "No Symfony project found, executing setup.sh..."
    /usr/local/bin/setup.sh
else
    echo "Symfony project found, setting up permissions..."
    
    # Create var directories if they don't exist
    echo "Setting up directory structure and permissions..."
    mkdir -p /var/www/html/var/cache /var/www/html/var/log /var/www/html/var/sessions
    
    # Set www-data group ownership and proper permissions
    chgrp -R www-data /var/www/html/var
    chmod -R 775 /var/www/html/var
    chmod -R g+s /var/www/html/var  # Set group sticky bit
    
    # Also ensure the main directory has proper group permissions
    chgrp www-data /var/www/html
    chmod 775 /var/www/html
    
    # Ensure public directory has correct permissions
    if [ -d "/var/www/html/public" ]; then
        chgrp www-data /var/www/html/public
        chmod 755 /var/www/html/public
    fi
    
    # Clear Symfony cache if it exists to avoid issues
    if [ -d "/var/www/html/var/cache" ] && [ -f "/var/www/html/bin/console" ]; then
        echo "Clearing Symfony cache..."
        su -s /bin/sh www-data -c "cd /var/www/html && php bin/console cache:clear --env=dev --no-interaction" 2>/dev/null || echo "Cache clear failed, continuing..."
    fi
    
    echo "Starting Apache..."
    apache2-foreground
fi
