#!/bin/bash

# Automated cPanel Migration Script with Logging
# Assumes SSH key-based access is already set up between source and destination

SOURCE_SERVER="source.server.ip"          # Replace with source server IP
DEST_SERVER="destination.server.ip"      # Replace with destination server IP
DEST_PATH="/home"                        # Destination path on new server
LOGFILE="/root/cpanel_migration.log"     # Log file to track progress

echo "Starting cPanel Migration: $(date)" >> $LOGFILE

# Loop through all cPanel accounts on the source server
for user in $(ssh root@$SOURCE_SERVER "ls /var/cpanel/users"); do
    echo "Starting migration for $user at $(date)" | tee -a $LOGFILE

    # Step 1: Package account on source server
    ssh root@$SOURCE_SERVER "/scripts/pkgacct $user --skiphomedircheck" >> $LOGFILE 2>&1

    # Step 2: Transfer backup to destination
    scp root@$SOURCE_SERVER:/home/cpmove-$user.tar.gz root@$DEST_SERVER:/home/ >> $LOGFILE 2>&1

    # Step 3: Restore account on destination
    ssh root@$DEST_SERVER "/scripts/restorepkg --force /home/cpmove-$user.tar.gz" >> $LOGFILE 2>&1

    # Step 4: Clean up backup file on destination (optional)
    ssh root@$DEST_SERVER "rm -f /home/cpmove-$user.tar.gz" >> $LOGFILE 2>&1

    echo "Finished migration for $user at $(date)" | tee -a $LOGFILE
done

echo "Migration completed: $(date)" >> $LOGFILE
