#!/bin/bash

# MySQL database credentials
DB_HOST="localhost"
DB_USER="your_username"
DB_PASS="your_password"
DB_NAME="your_database"

# Backup directory
BACKUP_DIR="/path/to/backup/directory"

# Email configuration
RECIPIENT="your_email@example.com"
SENDER="sender@example.com"
SMTP_SERVER="smtp.example.com"
SMTP_PORT="587"
SMTP_USERNAME="your_smtp_username"
SMTP_PASSWORD="your_smtp_password"

# Date format for backup file name
DATE=$(date +"%Y%m%d%H%M%S")

# Create backup file name
BACKUP_FILE="$BACKUP_DIR/db_backup_$DATE.sql"

# MySQL dump command to create the backup
mysqldump --host=$DB_HOST --user=$DB_USER --password=$DB_PASS $DB_NAME > $BACKUP_FILE

# Check if backup was successful
if [ $? -eq 0 ]; then
    echo "Database backup created successfully: $BACKUP_FILE"

    # Send email with backup status
    echo -e "Subject: MySQL Database Backup Status\n\nThe MySQL database backup was created successfully." | \
        /usr/sbin/sendmail -t -f $SENDER -s $SMTP_SERVER:$SMTP_PORT -xu $SMTP_USERNAME -xp $SMTP_PASSWORD $RECIPIENT
else
    echo "Error creating database backup."

    # Send email with backup status
    echo -e "Subject: MySQL Database Backup Status\n\nError creating MySQL database backup." | \
        /usr/sbin/sendmail -t -f $SENDER -s $SMTP_SERVER:$SMTP_PORT -xu $SMTP_USERNAME -xp $SMTP_PASSWORD $RECIPIENT
fi
