#!/bin/bash
# EXIM ERP Backup Script
# Runs daily via cron

set -e

# Configuration
BACKUP_DIR="/var/backups/exim-erp"
DATE=$(date +%Y%m%d_%H%M%S)
RETENTION_DAYS=30
DB_NAME="exim_erp"
DB_USER="exim_erp_user"
DB_PASS="EximErp@2025"
APP_DIR="/var/www/html/exim-erp"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'

print_status() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Create backup directory
mkdir -p "$BACKUP_DIR"

# Database backup
print_status "Backing up database..."
mysqldump -u "$DB_USER" -p"$DB_PASS" "$DB_NAME" | gzip > "$BACKUP_DIR/db_$DATE.sql.gz"
if [ $? -eq 0 ]; then
    print_status "Database backup completed: db_$DATE.sql.gz"
else
    print_error "Database backup failed!"
    exit 1
fi

# Application backup
print_status "Backing up application files..."
tar -czf "$BACKUP_DIR/app_$DATE.tar.gz" \
    --exclude='vendor' \
    --exclude='node_modules' \
    --exclude='.git' \
    --exclude='storage/logs/*' \
    --exclude='storage/framework/cache/*' \
    --exclude='storage/framework/sessions/*' \
    --exclude='storage/framework/views/*' \
    "$APP_DIR"

if [ $? -eq 0 ]; then
    print_status "Application backup completed: app_$DATE.tar.gz"
else
    print_error "Application backup failed!"
    exit 1
fi

# Cleanup old backups
print_status "Cleaning up backups older than $RETENTION_DAYS days..."
find "$BACKUP_DIR" -mtime +$RETENTION_DAYS -delete -type f
find "$BACKUP_DIR" -mtime +$RETENTION_DAYS -empty -type d -delete 2>/dev/null || true

# Calculate backup sizes
DB_SIZE=$(du -sh "$BACKUP_DIR/db_$DATE.sql.gz" | cut -f1)
APP_SIZE=$(du -sh "$BACKUP_DIR/app_$DATE.tar.gz" | cut -f1)
TOTAL_SIZE=$(du -sh "$BACKUP_DIR" | cut -f1)

print_status "Backup completed successfully!"
echo "  Database: $DB_SIZE"
echo "  Application: $APP_SIZE"
echo "  Total backup size: $TOTAL_SIZE"
echo "  Location: $BACKUP_DIR"
echo "  Date: $DATE"
