#!/bin/sh

# Requirements:
# $1: Source VM name
# $2: Destination VM name
# $3: Datastore name (e.g., datastore1)

if [ "$#" -ne 3 ]; then
    echo "Usage: $0 <Source_VM_Name> <Destination_VM_Name> <Datastore_Name>"
    echo "Example: $0 Ubuntu_Template Server01 datastore1"
    echo "List the VMs in ESXi:"
    vim-cmd vmsvc/getallvms
    echo "List the datastores in ESXi:"
    df -h
    exit 1
fi

SOURCE_VM="$1"
DEST_VM="$2"
DATASTORE="$3"
DATASTORE_PATH="/vmfs/volumes/${DATASTORE}"
SOURCE_DIR="${DATASTORE_PATH}/${SOURCE_VM}"
DEST_DIR="${DATASTORE_PATH}/${DEST_VM}"
SOURCE_VMX="${SOURCE_DIR}/${SOURCE_VM}.vmx"
DEST_VMX="${DEST_DIR}/${DEST_VM}.vmx"
SOURCE_VMDK="${SOURCE_DIR}/${SOURCE_VM}.vmdk"
DEST_VMDK="${DEST_DIR}/${DEST_VM}.vmdk"

# 1. Check the source VM and ensure it is powered off
echo "Checking source VM power state..."
VM_STATE=$(vim-cmd vmsvc/power.getstate $(vim-cmd vmsvc/getallvms | grep "${SOURCE_VM}" | awk '{print $1}') | grep "Powered" | awk '{print $4}')
if [ "${VM_STATE}" == "on" ]; then
    echo "ERROR: Source VM '${SOURCE_VM}' is running. Please power it off first."
    exit 1
fi

# 2. Create the destination directory
echo "Creating destination directory: ${DEST_DIR}"
mkdir -p "${DEST_DIR}" || { echo "ERROR: Unable to create destination directory."; exit 1; }

# 3. Copy and convert the virtual disk (VMDK)
# Use 'vmkfstools -i' to create a clone and optionally convert to thin provisioning (-d thin)
echo "Cloning and converting the virtual disk..."
vmkfstools -i "${SOURCE_VMDK}" "${DEST_VMDK}" -d zeroedthick || { echo "ERROR: vmkfstools failed."; exit 1; }

# 4. Copy and update the VM configuration file (VMX)
echo "Copying and updating the VMX configuration..."
if [ -f "${SOURCE_VMX}" ]; then
    # Copy the VMX and replace VM name/disk file references in the new config
    sed -e "s/${SOURCE_VM}/${DEST_VM}/g" "${SOURCE_VMX}" > "${DEST_VMX}"
else
    echo "ERROR: Source VMX file not found: ${SOURCE_VMX}"
    exit 1
fi

# 5. Register the new VM in the inventory
echo "Registering the new VM in the ESXi inventory..."
VMID=$(vim-cmd solo/registervm "${DEST_VMX}")

if [ $? -eq 0 ]; then
    echo "🎉 Clone completed! The new VM is registered with ID: ${VMID}"
    echo "Please power on the new VM and select 'I Copied it' if prompted."
else
    echo "ERROR: VM registration failed."
fi

