#!/bin/bash
# Backup script for Dine360 SaaS Multi-Tenant Databases
# Run this as a daily/weekly cron job on the host system

# Configuration
PG_USER="odoo"
PG_HOST="localhost"
PG_PORT="5432"
export PGPASSWORD="odoo_master_pass_2026"

BACKUP_DIR="/var/lib/odoo/backups"
S3_BUCKET="s3://dine360-backups"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")

mkdir -p "$BACKUP_DIR"

# Get all database names starting with dine360_
DATABASES=$(psql -h "$PG_HOST" -p "$PG_PORT" -U "$PG_USER" -d postgres -t -c "SELECT datname FROM pg_database WHERE datname LIKE 'dine360_%'")

for DB in $DATABASES; do
    echo "Starting backup of database: $DB..."
    BACKUP_FILE="$BACKUP_DIR/${DB}_${TIMESTAMP}.sql.gz"
    
    # Run pg_dump compressed with gzip
    if pg_dump -h "$PG_HOST" -p "$PG_PORT" -U "$PG_USER" -d "$DB" | gzip > "$BACKUP_FILE"; then
        echo "Successfully dumped to local storage: $BACKUP_FILE"
        
        # Upload to AWS S3 / DigitalOcean Spaces
        if aws s3 cp "$BACKUP_FILE" "$S3_BUCKET/$DB/${DB}_${TIMESTAMP}.sql.gz"; then
            echo "Uploaded successfully to S3 bucket."
        else
            echo "Error: Upload to S3 failed." >&2
        fi
    else
        echo "Error: pg_dump failed for database $DB" >&2
    fi
done

# Retain local files for 7 days, delete older ones
find "$BACKUP_DIR" -type f -name "dine360_*.sql.gz" -mtime +7 -delete

echo "Dine360 backups verification completed at $(date)"
