#!/bin/bash set -e echo "==========================================" echo "🚀 Starting PostgreSQL + pgweb Space" echo "==========================================" export HF_TOKEN="${HF_TOKEN:-}" export XET_DATASET="${XET_DATASET:-}" export PGPASSWORD="${POSTGRES_PASSWORD:-postgres123}" # ============================================ # RESTORE FROM XET STORAGE # ============================================ if [ -n "$HF_TOKEN" ] && [ -n "$XET_DATASET" ]; then echo "đŸ“Ļ Checking for backup in Xet dataset..." python3 << 'RESTORE_SCRIPT' import os import sys from pathlib import Path try: from huggingface_hub import hf_hub_download, list_repo_files hf_token = os.environ.get('HF_TOKEN') dataset_id = os.environ.get('XET_DATASET') if not hf_token or not dataset_id: sys.exit(0) try: files = list_repo_files(dataset_id, repo_type="dataset", token=hf_token) if 'backup/pg_backup.sql' in files: print(f"✅ Found backup in {dataset_id}") Path('/data/backup').mkdir(parents=True, exist_ok=True) hf_hub_download( repo_id=dataset_id, filename="backup/pg_backup.sql", repo_type="dataset", token=hf_token, local_dir="/data" ) print("đŸ“Ĩ Backup downloaded") else: print("â„šī¸ No backup found, starting fresh") except Exception as e: print(f"â„šī¸ Dataset access note: {e}") except Exception as e: print(f"âš ī¸ Restore check: {e}") RESTORE_SCRIPT fi # ============================================ # INITIALIZE POSTGRESQL # ============================================ echo "đŸ—„ī¸ Setting up PostgreSQL..." if [ ! -f "/data/postgres/PG_VERSION" ]; then echo "📝 Initializing new PostgreSQL database..." sudo -u postgres /usr/lib/postgresql/15/bin/initdb -D /data/postgres -E UTF8 --locale=C # Configure authentication echo "local all all trust" > /data/postgres/pg_hba.conf echo "host all all 127.0.0.1/32 trust" >> /data/postgres/pg_hba.conf echo "host all all ::1/128 trust" >> /data/postgres/pg_hba.conf # Start temporarily sudo -u postgres /usr/lib/postgresql/15/bin/pg_ctl -D /data/postgres -l /tmp/pg_init.log start sleep 3 # Create database sudo -u postgres createdb appdb echo "✅ Database 'appdb' created" # Restore backup if exists if [ -f "/data/backup/pg_backup.sql" ]; then echo "🔄 Restoring from backup..." sudo -u postgres psql -d appdb -f /data/backup/pg_backup.sql 2>/dev/null || true echo "✅ Restore completed" fi # Stop temporary instance sudo -u postgres /usr/lib/postgresql/15/bin/pg_ctl -D /data/postgres stop sleep 2 echo "✅ PostgreSQL initialized" else echo "✅ PostgreSQL data exists" fi chown -R postgres:postgres /data/postgres chmod 700 /data/postgres echo "==========================================" echo "🎉 Starting services..." echo "" echo "📊 Web UI: https://your-space.hf.space" echo "đŸ—„ī¸ Database: appdb" echo "==========================================" exec /usr/bin/supervisord -c /etc/supervisor/conf.d/supervisord.conf