#!/bin/bash

# Function to restore database from a backup file
restore_database() {
    local backup_file="$1"
    echo "Restoring database from $backup_file..."
    gunzip < "$backup_file" | mysql -h "$DB_HOST" -u "$DB_USER" -p"$DB_PASSWORD" "$DB_NAME"
    echo "Database restored from $backup_file."
}

# Function to backup the current database
backup_database() {
    local backup_file="$1"
    # Delete specified backup file if it exists
if [ -n "$backup_file" ] && [ -f "$backup_file" ]; then
    echo "Deleting existing backup file: $backup_file"
    rm "$backup_file"
fi
    echo "Backing up database to $backup_file..."
    mysqldump -h "$DB_HOST" -u "$DB_USER" -p"$DB_PASSWORD" "$DB_NAME" --single-transaction --set-gtid-purged=OFF | gzip > "$backup_file"
    echo "Database backed up to $backup_file."
}

# Parse script arguments
ACTION=$1
FILE=$2
DB_BACKUP_PATH="$(pwd)/mysql_backups" # Default backup directory

# Create backup directory if it doesn't exist
mkdir -p "$DB_BACKUP_PATH"

# Define the database credentials
DB_NAME=$(wp config get DB_NAME --allow-root)
DB_USER=$(wp config get DB_USER --allow-root)
DB_PASSWORD=$(wp config get DB_PASSWORD --allow-root)
DB_HOST=$(wp config get DB_HOST --allow-root)

# Perform the requested action
case $ACTION in
    restore)
        if [ -n "$FILE" ]; then
            restore_database "$FILE"
        else
            echo "No backup file specified for restore. Restoring from the latest backup."
            LAST_BACKUP_FILE=$(ls -t "$DB_BACKUP_PATH"/*_backup_*.sql.gz | head -n 1)
            if [ -n "$LAST_BACKUP_FILE" ]; then
                restore_database "$LAST_BACKUP_FILE"
            else
                echo "No backup files found."
            fi
        fi
        ;;
    backup)
        if [ -n "$FILE" ]; then
            BACKUP_FILE="$FILE"
        else
            CURRENT_TIMESTAMP=$(date +"%Y%m%d%H%M%S")
            BACKUP_FILE="$DB_BACKUP_PATH/${DB_NAME}_backup_$CURRENT_TIMESTAMP.sql.gz"
        fi
        backup_database "$BACKUP_FILE"
        ;;
    *)
        echo "Invalid action. Usage: $0 {restore|backup} [file]"
        exit 1
        ;;
esac

#within script
    # Restore the database from a specified backup file
    #./install_mysql_restore_backup.sh restore "path/to/backup_file.sql.gz"

    # Perform your operations here...

    # Backup the database with a specified backup file name
    #./install_mysql_restore_backup.sh backup "path/to/new_backup_file.sql.gz"
#from terminal
#./install_mysql_restore_backup.sh restore "path/to/backup_file.sql.gz"
#./install_mysql_restore_backup.sh restore
#./install_mysql_restore_backup.sh backup "path/to/new_backup_file.sql.gz"
#./install_mysql_restore_backup.sh backup
