FROM python:3.9

# Install system dependencies
RUN apt-get update && apt-get install -y libgl1-mesa-glx

# Set the working directory
WORKDIR /code

# Copy requirements file and install dependencies
COPY ./requirements.txt /code/requirements.txt
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt

# Copy the Gunicorn configuration file
COPY ./gunicorn_config.py /code/gunicorn_config.py

# Copy the rest of the application files
COPY . .

# Create a directory for the instance folder and set permissions
RUN mkdir -p /code/instance \
    && chmod 777 /code/instance \
    && mkdir -p /code/media \
    && chmod 777 /code/media \
    && chmod 777 /code

# Create a non-root user and switch to it
RUN useradd -ms /bin/bash myuser
USER myuser

# Command to run the application with Gunicorn and custom configuration
CMD ["gunicorn", "-b", "0.0.0.0:7860", "-c", "gunicorn_config.py", "main:app"]