#!/bin/bash

# Flowieons Backup Script
# Automatically creates DB and storage backups and implements retention policy.

# Configuration
DB_NAME="flowieons"
DB_USER="root"
# DB_PASS="password" # Provide via env variable or .my.cnf
BACKUP_DIR="/home/backups/flowieons"
STORAGE_DIR="/var/www/flowieons/storage/app/public" # Adjust to actual path

DATE_STR=$(date +'%Y%m%d_%H%M%S')
DAILY_DIR="$BACKUP_DIR/daily"
WEEKLY_DIR="$BACKUP_DIR/weekly"
MONTHLY_DIR="$BACKUP_DIR/monthly"

mkdir -p "$DAILY_DIR"
mkdir -p "$WEEKLY_DIR"
mkdir -p "$MONTHLY_DIR"

# Database Backup
DB_BACKUP_FILE="$DAILY_DIR/db_$DATE_STR.sql.gz"
echo "Creating database backup..."
# mysqldump -u $DB_USER -p$DB_PASS $DB_NAME | gzip > $DB_BACKUP_FILE
mysqldump -u $DB_USER $DB_NAME | gzip > $DB_BACKUP_FILE

# Storage Backup
STORAGE_BACKUP_FILE="$DAILY_DIR/storage_$DATE_STR.tar.gz"
echo "Creating storage backup..."
tar -czf $STORAGE_BACKUP_FILE -C $STORAGE_DIR .

# Implement retention logic
# Daily: 7 days
echo "Cleaning up daily backups older than 7 days..."
find $DAILY_DIR -type f -name "*.gz" -mtime +7 -exec rm {} \;

# Weekly: Copy a daily backup to weekly if it's Sunday
DAY_OF_WEEK=$(date +%u)
if [ "$DAY_OF_WEEK" -eq 7 ]; then
    echo "Creating weekly backup..."
    cp $DB_BACKUP_FILE "$WEEKLY_DIR/db_$DATE_STR.sql.gz"
    cp $STORAGE_BACKUP_FILE "$WEEKLY_DIR/storage_$DATE_STR.tar.gz"
    
    # Keep weekly for 4 weeks (28 days)
    echo "Cleaning up weekly backups older than 28 days..."
    find $WEEKLY_DIR -type f -name "*.gz" -mtime +28 -exec rm {} \;
fi

# Monthly: Copy a daily backup to monthly if it's the 1st of the month
DAY_OF_MONTH=$(date +%d)
if [ "$DAY_OF_MONTH" -eq "01" ]; then
    echo "Creating monthly backup..."
    cp $DB_BACKUP_FILE "$MONTHLY_DIR/db_$DATE_STR.sql.gz"
    cp $STORAGE_BACKUP_FILE "$MONTHLY_DIR/storage_$DATE_STR.tar.gz"
    
    # Keep monthly for 6 months (180 days)
    echo "Cleaning up monthly backups older than 180 days..."
    find $MONTHLY_DIR -type f -name "*.gz" -mtime +180 -exec rm {} \;
fi

echo "Backup process completed successfully."
