FROM python:3.11-slim

# Set working directory
WORKDIR /app

# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy application code
COPY app.py models.py .
COPY templates/ templates/
COPY static/ static/
COPY data/ data/

# Create data directory with proper permissions
RUN mkdir -p data/icons && chmod 755 data && chmod 755 data/icons && chmod +x data/servctl.sh

# Create startup script
RUN echo '#!/bin/bash

# Check if database file exists
if [ ! -f "/app/data/dashboard.db" ]; then
    echo "Creating default database..."
    # Run the application once to create the database
    python app.py &
    sleep 5
    pkill -f "python app.py"
    sleep 2
    echo "Database created successfully"
fi

# Check if servctl.sh exists in data directory
if [ ! -f "/app/data/servctl.sh" ]; then
    echo "Copying servctl.sh to data directory..."
    cp /app/servctl.sh /app/data/
    chmod +x /app/data/servctl.sh
    echo "servctl.sh copied successfully"
fi

# Start the application
echo "Starting Servboard..."
python app.py' > /app/startup.sh && chmod +x /app/startup.sh

# Expose port
EXPOSE 5000

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:5000/health')" || exit 1

# Start application using startup script
CMD ["/app/startup.sh"]
