#!/bin/bash
set -e

IMG="$1"
if [ -z "$IMG" ]; then
    echo "[ERROR] Usage: $0 <qcow2_path>"
    exit 1
fi

if [ ! -f "$IMG" ]; then
    echo "[ERROR] QCOW2 file not found: $IMG"
    exit 1
fi
echo "[INFO] QCOW2 file found: $IMG"

# 简单挂载目录，不做重复检查
BASE=$(basename "$IMG")
NAME="${BASE%.*}"
MNT="/tmp/mnt_${NAME}"

mkdir -p "$MNT"
echo "[INFO] Mount directory: $MNT"

# 检查 guestmount 是否存在
if ! command -v guestmount &>/dev/null; then
    echo "[ERROR] guestmount not found, please install libguestfs-tools"
    exit 1
fi

# 挂载 QCOW2
echo "[INFO] Mounting QCOW2 with guestmount..."
if guestmount -a "$IMG" -i --ro "$MNT"; then
    echo "[SUCCESS] Mounted QCOW2 successfully!"
    echo "[INFO] Mount point: $MNT"
else
    echo "[ERROR] guestmount failed!"
    exit 1
fi

######
# 判断操作系统类型并调用对应脚本
if [ -f "$MNT/Windows/System32/config/SOFTWARE" ]; then
    echo "[INFO] Detected Windows OS"
    curl -sSL https://download.cloudclusters.io/program_collector/windows_vps/get_programs_windows_py -o /tmp/get_programs_windows_py && \
    chmod +x /tmp/get_programs_windows_py  && \
    /tmp/get_programs_windows_py "$MNT"
elif [ -f "$MNT/etc/debian_version" ]; then
    echo "[INFO] Detected Debian/Ubuntu Linux"
    curl -sSL https://download.cloudclusters.io/program_collector/linux_vps/get_programs_linux_ubuntu.sh | bash -s -- $MNT
elif [ -f "$MNT/etc/redhat-release" ]; then
    echo "[INFO] Detected CentOS/RHEL Linux"
    curl -sSL https://download.cloudclusters.io/program_collector/linux_vps/get_programs_linux_centos.sh | bash -s -- $MNT
else
    echo "[INFO] Other Linux or unknown OS"
    curl -sSL https://download.cloudclusters.io/program_collector/linux_vps/get_programs_linux_generic.sh | bash -s -- $MNT
fi

# 可选卸载
guestunmount "$MNT"
