#!/bin/bash

# This script is used to start the web application server
# inside the Docker container.

# if you edit this file you need to rebuild the image, for example:
# docker-compose down && docker-compose build --no-cache

CONFIG_FILE="/app/.env"

# Check if the config file exists
if [ ! -f "$CONFIG_FILE" ]; then
    echo "Config file not found: $CONFIG_FILE"
    exit 1
fi

echo "Config file found: $CONFIG_FILE"

if [ ! -d "/venv/bin" ]; then
    echo "Virtualenv not found, creating..."
    python3 -m venv /venv
    # Install required Python packages
    echo "Installing required Python packages..."
    /venv/bin/pip install --upgrade pip
    /venv/bin/pip install --no-cache-dir -r /app/requirements.txt
fi


# Set gunicorn flags based on flask_env
if [ "$FLASK_ENV" = "development" ]; then
    GUNICORN_FLAGS="--reload --log-level debug"
else
    GUNICORN_FLAGS=""
fi

echo "Starting server with Flask environment: $FLASK_ENV"
/venv/bin/gunicorn $GUNICORN_FLAGS -c /app/gunicorn.conf.py "app:create_app()"
