#!/bin/bash # # Database Replication Setup for PostgreSQL Streaming Replication # Run on PRIMARY server first, then on SECONDARY # set -eu MODE="${1:-help}" PRIMARY_IP="192.168.1.100" # Update with primary server IP SECONDARY_IP="72.62.39.24" POSTGRES_PASSWORD="your_postgres_password" # Update from .env REPLICATION_USER="replicator" REPLICATION_PASSWORD="your_replication_password" # Generate strong password log() { echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*" } setup_primary() { log "🔧 Setting up PRIMARY database for replication..." # Create replication user docker exec trading-bot-postgres psql -U postgres -d trading_bot_v4 <<-EOF -- Create replication user CREATE USER ${REPLICATION_USER} WITH REPLICATION ENCRYPTED PASSWORD '${REPLICATION_PASSWORD}'; -- Grant necessary privileges GRANT CONNECT ON DATABASE trading_bot_v4 TO ${REPLICATION_USER}; EOF log "✅ Replication user created" # Configure pg_hba.conf for replication docker exec trading-bot-postgres bash -c "cat >> /var/lib/postgresql/data/pg_hba.conf <> /var/lib/postgresql/data/postgresql.conf < /tmp/trading_bot_backup.sql" echo " rsync -avz /tmp/trading_bot_backup.sql ${SECONDARY_IP}:/tmp/" log "Run on SECONDARY to restore:" echo " docker exec -i trading-bot-postgres psql -U postgres trading_bot_v4 < /tmp/trading_bot_backup.sql" } case "$MODE" in primary) setup_primary ;; secondary) setup_secondary ;; sync) simplified_sync ;; help|*) echo "Usage: $0 {primary|secondary|sync}" echo "" echo "primary - Configure primary DB for replication" echo "secondary - Configure secondary DB as replica" echo "sync - Show commands for manual DB sync" echo "" echo "⚠️ IMPORTANT: Update IP addresses and passwords in script first!" exit 1 ;; esac