#!/bin/bash
cd /opt/task-team || exit 1
BACKUP_DIR="/opt/task-team/backups"
DATE=$(date +%Y%m%d_%H%M)
PGDUMP="/usr/lib/postgresql/18/bin/pg_dump"
mkdir -p $BACKUP_DIR

# Dump all databases
PGPASSWORD="TaskTeam2026!" $PGDUMP -h 10.10.10.10 -U taskteam -d taskteam -F c -f "$BACKUP_DIR/taskteam_$DATE.dump"

if [ $? -eq 0 ]; then
    # Compress
    gzip -f "$BACKUP_DIR/taskteam_$DATE.dump" 2>/dev/null
    echo "$(date "+%Y-%m-%d %H:%M:%S") OK: taskteam_$DATE.dump.gz"
else
    echo "$(date "+%Y-%m-%d %H:%M:%S") FAIL: pg_dump exited with error"
fi

# Keep last 14 daily backups
find $BACKUP_DIR -name "*.dump.gz" -mtime +14 -delete
find $BACKUP_DIR -name "*.dump" -mtime +14 -delete

ls -lh $BACKUP_DIR/ | tail -5
