#!/usr/bin/env bash
# exit on error
set -o errexit

# Install system dependencies
apt-get update && apt-get install -y \
    libmagic1 \
    python3-dev \
    python3-pip \
    python3-setuptools \
    python3-wheel \
    python3-cffi \
    libcairo2 \
    libpango-1.0-0 \
    libpangocairo-1.0-0 \
    libgdk-pixbuf2.0-0 \
    libffi-dev \
    shared-mime-info \
    libblas-dev \
    liblapack-dev \
    libatlas-base-dev \
    gfortran \
    pkg-config \
    libfreetype6-dev

# Install Python dependencies with limited concurrent jobs to reduce memory usage
pip install -r requirements.txt --no-cache-dir

# Pre-build matplotlib font cache to avoid runtime building
python -c "
import matplotlib.pyplot as plt
plt.figure()
plt.close()
"

# Clear pip cache to free up memory
rm -rf ~/.cache/pip

# Run setup.py with reduced memory usage
export PYTHONMALLOC=debug
export MALLOC_TRIM_THRESHOLD_=65536
python setup.py develop

# Collect static files
python manage.py collectstatic --no-input

# Apply database migrations
python manage.py migrate