#!/bin/bash

# Function to display help
display_help() {
    echo "Usage: $0 [options]"
    echo ""
    echo "Options:"
    echo "  -old IP_ADDRESS       Specify the old IP address to be replaced."
    echo "  -new IP_ADDRESS       Specify the new IP address to use."
    echo "  -domain DOMAIN_NAME   Specify a single domain for the IP change. If omitted, all domains are processed by default."
    echo "  -all                  Explicitly specify to change the IP address for all domains."
    echo "  -v, --verbose         Enable verbose output."
    echo "  -h, --help            Display this help message and exit."
    echo ""
    echo "This script updates the IP addresses associated with domains in a Plesk database."
    echo "By default, without -domain or -all, the script will assume the change is for all domains."
    exit 0
}

# Initialize variables
old_ip=""
new_ip=""
domain_name=""
process_all=false
verbose=0

# Parse command line options
while [[ "$#" -gt 0 ]]; do
    case "$1" in
        -old) old_ip="$2"; shift 2 ;;
        -new) new_ip="$2"; shift 2 ;;
        -domain) domain_name="$2"; shift 2 ;;
        -all) process_all=true; shift ;;
        -v|--verbose) verbose=1; shift ;;
        -h|--help) display_help ;;
        *) echo "Unknown parameter: $1"; exit 1 ;;
    esac
done

# Validate mandatory options
if [[ -z "$old_ip" || -z "$new_ip" ]]; then
    echo "Both old and new IP addresses must be specified."
    exit 1
fi

# Define the scope of IP change based on flags or defaults
scope_message="FOR ALL DOMAINS"
if [[ -n "$domain_name" ]]; then
    scope_message="FOR THE DOMAIN $domain_name"
elif [[ "$process_all" = true ]]; then
    scope_message="FOR ALL DOMAINS"
fi

# Ask for confirmation before proceeding
read -p "Do you want to proceed with the IP address change $scope_message? (y/n): " confirm
if [[ "$confirm" != "y" ]]; then
    echo "IP address change cancelled."
    exit 0
fi

# Perform database dump
timestamp=$(date +%Y-%m-%d-%H-%M-%S)
backup_file="$HOME/psa-$timestamp.sql"
plesk db dump > "$backup_file"
echo "Database backup created at $backup_file"

# Execute SQL transaction
if [[ -n "$domain_name" ]]; then
    # Process single domain
    domain_names="$domain_name"
else
    # Process all domains
    domain_names=$(plesk db -Ne "SELECT name FROM domains")
fi

echo "$domain_names" | while read line; do
    if [ $verbose -eq 1 ]; then
        echo "Starting transaction for domain: $line"
    fi
    output=$(plesk db "START TRANSACTION;
        select @ip_id := id from IP_Addresses where ip_address='$old_ip';
        set @domain_name := '$line';
        select @ip_id_new := id from IP_Addresses where ip_address='$new_ip';
        update IpAddressesCollections ipac
            INNER JOIN DomainServices ds ON ds.ipCollectionId = ipac.ipCollectionId
            INNER JOIN domains d ON d.id = ds.dom_id
            JOIN IP_Addresses ip on ipac.ipaddressid=ip.id
        set ipac.ipAddressId=@ip_id_new
        WHERE (ds.type = 'web' OR ds.type = 'mail') and ipac.ipAddressId = @ip_id and d.name=@domain_name;
        COMMIT;")
    if [ $? -eq 0 ]; then
        echo "IP address change for domain $line successful."
    else
        echo "Error occurred: $output"
        exit 1
    fi
done

if [ $verbose -eq 1 ]; then
    echo "All transactions completed."
fi
