#!/bin/bash set -e echo "═══════════════════════════════════════════════════════════" echo "MITAI JINKENDO - Backend Startup (v9b)" echo "═══════════════════════════════════════════════════════════" # ── PostgreSQL Connection Check ─────────────────────────────── echo "" echo "Checking PostgreSQL connection..." MAX_RETRIES=30 RETRY_COUNT=0 until PGPASSWORD=$DB_PASSWORD psql -h "$DB_HOST" -U "$DB_USER" -d "$DB_NAME" -c '\q' 2>/dev/null; do RETRY_COUNT=$((RETRY_COUNT + 1)) if [ $RETRY_COUNT -ge $MAX_RETRIES ]; then echo "✗ PostgreSQL not ready after ${MAX_RETRIES} attempts" echo " Exiting..." exit 1 fi echo " Waiting for PostgreSQL... (attempt $RETRY_COUNT/$MAX_RETRIES)" sleep 2 done echo "✓ PostgreSQL ready" # ── Schema Initialization ────────────────────────────────────── echo "" echo "Checking database schema..." # Check if profiles table exists TABLE_EXISTS=$(PGPASSWORD=$DB_PASSWORD psql -h "$DB_HOST" -U "$DB_USER" -d "$DB_NAME" -tAc \ "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='public' AND table_name='profiles'") if [ "$TABLE_EXISTS" = "0" ]; then echo " Schema not found, initializing..." PGPASSWORD=$DB_PASSWORD psql -h "$DB_HOST" -U "$DB_USER" -d "$DB_NAME" -f /app/schema.sql echo "✓ Schema loaded from schema.sql" else echo "✓ Schema already exists" fi # ── Auto-Migration (SQLite → PostgreSQL) ─────────────────────── echo "" echo "Checking for SQLite data migration..." SQLITE_DB="/app/data/bodytrack.db" PROFILE_COUNT=$(PGPASSWORD=$DB_PASSWORD psql -h "$DB_HOST" -U "$DB_USER" -d "$DB_NAME" -tAc \ "SELECT COUNT(*) FROM profiles") if [ -f "$SQLITE_DB" ] && [ "$PROFILE_COUNT" = "0" ]; then echo " SQLite database found and PostgreSQL is empty" echo " Starting automatic migration..." python /app/migrate_to_postgres.py echo "✓ Migration completed" elif [ -f "$SQLITE_DB" ] && [ "$PROFILE_COUNT" != "0" ]; then echo "⚠ SQLite DB exists but PostgreSQL already has $PROFILE_COUNT profiles" echo " Skipping migration (already migrated)" elif [ ! -f "$SQLITE_DB" ]; then echo "✓ No SQLite database found (fresh install or already migrated)" else echo "✓ No migration needed" fi # ── Start Application ────────────────────────────────────────── echo "" echo "═══════════════════════════════════════════════════════════" echo "Starting FastAPI application..." echo "═══════════════════════════════════════════════════════════" echo "" exec uvicorn main:app --host 0.0.0.0 --port 8000