#!/bin/bash
#
# This script syncs the production database to the development (staging) database.
# It should be run via a cron job on the server.
# WARNING: This script completely overwrites the development database.

set -e

# --- Configuration ---
PROD_DB_CONTAINER="mold_cost_db"
DEV_DB_CONTAINER="mold_cost_db_development"
PROD_DB_NAME="mold_cost"
DEV_DB_NAME="mold_cost_development"
BACKUP_FILE="/tmp/prod_db_dump.sql"
LOG_FILE="/home/jimmyg/mold_cost_online_tool/logs/db_sync.log"

# --- Main Logic ---
echo "---" >> "$LOG_FILE"
echo "[$(date)] Starting database sync from Production to Development..." >> "$LOG_FILE"

# 1. Dump the production database
echo "Dumping production database ('$PROD_DB_NAME') from container '$PROD_DB_CONTAINER'..." >> "$LOG_FILE"
podman exec "$PROD_DB_CONTAINER" pg_dump -U postgres -d "$PROD_DB_NAME" -c -C > "$BACKUP_FILE"
echo "Production database dump complete." >> "$LOG_FILE"

# 2. Restore the dump to the development database
echo "Restoring dump to development database ('$DEV_DB_NAME') in container '$DEV_DB_CONTAINER'..." >> "$LOG_FILE"
# We connect to the default 'postgres' db to drop/recreate the development db
cat "$BACKUP_FILE" | podman exec -i "$DEV_DB_CONTAINER" psql -U postgres -d postgres
echo "Development database restore complete." >> "$LOG_FILE"

# 3. Clean up the backup file
rm "$BACKUP_FILE"
echo "Backup file cleaned up." >> "$LOG_FILE"

echo "[$(date)] Database sync finished successfully." >> "$LOG_FILE" 