#!/bin/bash

# Check if a parameter was provided
if [ -z "$1" ]; then
  echo "Error: No number provided. Please provide a number as a parameter."
  exit 1
fi

# Assign the parameter to a variable
number=$1

# Database details
database="commons_wp"
# Ensure your .my.cnf file is set up for passwordless access

# Directory for backups
backup_dir=~/data-restore-2023-10-11/production-backups
files_backup_dir=${backup_dir}/files/${number}

# Source directory for files
source_dir=/PROD_WWW/html/commons/www/wp-content/blogs.dir/${number}/

# Create the directories if they don't exist
mkdir -p "$backup_dir"
mkdir -p "$files_backup_dir"

# Rsync files from source to backup directory
rsync -avzh --progress "${source_dir}" "${files_backup_dir}"

# Get the list of tables like 'wp_{number}_%'
tables=$(mysql  -D "$database" -e "SHOW TABLES LIKE 'wp\_${number}\_%';" | awk '{ print $1 }' | grep -v '^Tables' | tr '\n' ' ')

# Check if tables were found
if [ -z "$tables" ]; then
  echo "No tables found for the provided number: $number"
  exit 1
fi

# Dump the tables
mysqldump  "$database" $tables > "${backup_dir}/wp_${number}_backup.sql"

# Check if the mysqldump was successful
if [ $? -eq 0 ]; then
  echo "Backup successful. Files and database backup created in ${backup_dir}"
else
  echo "Database backup failed."
fi

