#!/bin/sh

echo "[INFO] Backup entry success"

# Configuration 
PG_CONTAINER_NAME=$(docker ps --filter "name=_db" --format "{{.Names}}" | head -n 1)
PG_USER="user"
PG_PASSWORD="password"
PG_DB="mydatabase"
BACKUP_DIR="/backups"
LOG_DIR="/backups/logs"
RETENTION_DAYS=1
TIMESTAMP=$(date +"%Y%m%d-%H%M%S")
FILENAME="$BACKUP_DIR/backup-$TIMESTAMP.sql"
LOGFILE="$LOG_DIR/backup-$TIMESTAMP.log"

# Setup Directories
mkdir -p "$BACKUP_DIR"
mkdir -p "$LOG_DIR"

# Begin Logging 
exec > "$LOGFILE" 2>&1

echo "[INFO] Backup script started at $TIMESTAMP"
echo "[INFO] Backing up database '$PG_DB' from container '$PG_CONTAINER_NAME'..."

# Perform Backup 
PGPASSWORD="$PG_PASSWORD" pg_dump -h db -U "$PG_USER" -d "$PG_DB" > "$FILENAME"

if [ $? -eq 0 ]; then
    echo "[INFO] Backup successful: $FILENAME"
else
    echo "[ERROR] Backup failed!" >&2
    exit 1
fi

# Rotate Old Backups 
echo "[INFO] Removing backups older than $RETENTION_DAYS days..."
find "$BACKUP_DIR" -type f -name "backup-*.sql" -mtime +$RETENTION_DAYS -exec rm -f {} \;

# Rotate Old Logs 
echo "[INFO] Removing logs older than $RETENTION_DAYS days..."
find "$LOG_DIR" -type f -name "backup-*.log" -mtime +$RETENTION_DAYS -exec rm -f {} \;

echo "[INFO] Backup and cleanup completed at $(date +"%Y%m%d-%H%M%S")"

