#!/bin/bash
# =========================================================
# BACKUP DATABASE - Backup giornaliero PostgreSQL
# =========================================================

BACKUP_DIR="/opt/ids/backups"
DB_NAME="ids_database"
DB_USER="ids_user"
DB_HOST="127.0.0.1"
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="$BACKUP_DIR/ids_db_$DATE.sql.gz"
LOG_FILE="/var/log/ids/backup.log"

mkdir -p "$BACKUP_DIR"
mkdir -p /var/log/ids

echo "[$(date)] Backup database avviato..." >> "$LOG_FILE"

# Backup database (compressa)
PGPASSWORD=$PGPASSWORD pg_dump -h "$DB_HOST" -U "$DB_USER" "$DB_NAME" | gzip > "$BACKUP_FILE"

if [ $? -eq 0 ]; then
    SIZE=$(du -h "$BACKUP_FILE" | cut -f1)
    echo "[$(date)] Backup completato: $BACKUP_FILE ($SIZE)" >> "$LOG_FILE"
    
    # Keep only last 7 backups
    cd "$BACKUP_DIR"
    ls -t ids_db_*.sql.gz | tail -n +8 | xargs -r rm
    echo "[$(date)] Cleanup backup vecchi completato" >> "$LOG_FILE"
else
    echo "[$(date)] ERRORE backup database!" >> "$LOG_FILE"
    exit 1
fi
