#!/bin/bash
set -e

# Define variables
ISO_URL="http://172.29.48.5/VMTOOLS/3.2.0/SMTX_VMTOOLS-3.2.0-2501210639.iso"
ISO_FILE="/tmp/vmtools.iso"
MOUNT_POINT="/mnt/wuke-vmtools"

# 1. Install required packages
if command -v yum >/dev/null 2>&1; then
    echo "Installing dependencies using yum..."
    yum install -y tar bzip2
elif command -v apt >/dev/null 2>&1; then
    echo "Installing dependencies using apt..."
    apt update
    apt install -y tar bzip2
else
    echo "Unsupported OS: yum or apt not found."
    exit 1
fi

# 2. Download the ISO file
echo "Downloading VMTools ISO..."
curl -o "$ISO_FILE" "$ISO_URL"

# 3. Check if /mnt/wuke-vmtools exists
if [ -d "$MOUNT_POINT" ]; then
    echo "Directory $MOUNT_POINT exists, removing..."
    umount "$MOUNT_POINT" || true
    rm -rf "$MOUNT_POINT"
fi

echo "Creating directory $MOUNT_POINT..."
mkdir -p "$MOUNT_POINT"

# 4. Mount the ISO
echo "Mounting ISO file to $MOUNT_POINT..."
mount -o loop "$ISO_FILE" "$MOUNT_POINT"

# 5. Execute the installation script
echo "Running VMTools installation script..."
bash "$MOUNT_POINT/SMTX_VM_TOOLS_INSTALL.sh"

# 6. Cleanup
echo "Cleaning up temporary files..."
umount "$MOUNT_POINT" || true
rm -f "$ISO_FILE"
rm -rf "$MOUNT_POINT"

echo "Installation and cleanup completed."