#!/bin/bash

help_message() {
    echo "Usage: $(basename $0) <vm_id> '<command>'
    
Options:
    --help      Show this help message
    --version   Show the version of the script
    
Arguments:
    vm_id       The ID of the virtual machine
    command     The command to execute in the VM (must be quoted)

Example:
    $(basename $0) 100 'ls -la'
    $(basename $0) 101 'cat /etc/hosts'"
}

if [ "$1" = "--help" ]; then
    help_message
    exit 0
fi

# Version
VERSION="0.1"

if [ "$1" = "--version" ]; then
    echo "guexec version $VERSION"
    echo "Guest Execute Script"
    echo "Copyright (C) 2024 Pasukan Langit"
    exit 0
fi

if [ -z "$1" ] || [ -z "$2" ]; then
    help_message
    exit 1
fi

if ! [[ "$1" =~ ^[0-9]+$ ]]; then
    echo "Error: vm_id must be a number"
    help_message
    exit 1
fi

vm_id="$1"
shift
script="$*"

json_output=$(qm guest exec "$vm_id" --timeout 0 -- /bin/bash -c "$script")

if echo "$json_output" | jq -e 'has("err-data")' > /dev/null; then
    echo "Error found: $(echo "$json_output" | jq -r '.["err-data"]')"
elif echo "$json_output" | jq -e 'has("out-data")' > /dev/null; then
    echo "$(echo "$json_output" | jq -r '.["out-data"]')"
else
    echo "Command executed successfully"
fi
