#!/bin/bash -x
exec >> /tmp/swtpm-qemu.log 2>&1

# 参数定义
VM_NAME=$1        # 虚拟机名称
EVENT=$2          # 事件类型
SUBEVENT=$3       # 子事件类型

# 仅处理虚拟机启动的 `begin` 阶段
if [[ "$EVENT" == "start" ]]; then
    # 找到虚拟机的 UUID 和 .files 路径
    VM_UUID=$(xmlstarlet sel -t -v "/domain/uuid" /etc/libvirt/qemu/"$VM_NAME".xml 2>/dev/null)

    if [[ -z "$VM_UUID" ]]; then
        echo "$(date): Failed to retrieve UUID for $VM_NAME"
        exit 1
    fi

    # This script is restricted by /etc/apparmor.d/usr.sbin.libvirtd rules
    # Use systemctl to bypass
    systemctl start vm-swtpm-apparmor@$VM_UUID.service
fi

exit 0
