#! /bin/bash
# vim: shiftwidth=4 tabstop=4 expandtab

if in_array "${COMMAND_ARGS[0]}" --help -h help; then
    echo "$COMMAND [VM]"
    echo "$COMMAND [-r|--reverse] [PID]"
    if [ "${COMMAND_ARGS[1]}" == "details" ]; then
        echo "  Find the PID of VM from its name or its name from its PID with the -r/--reverse" \
            "parameter"
    fi
    return
fi

check_generate_script_not_supported

REVERSE=0
VM_OR_PID=""
for i in "${COMMAND_ARGS[@]}"; do
    case $i in
        -r|--reverse)
            REVERSE=1
            ;;
        *)
            if [[ -z "$VM_OR_PID" ]]; then
                VM_OR_PID=$i
            else
                usage "Unknown argument '$i'"
            fi
            ;;
    esac
done

if [[ $REVERSE -eq 1 ]]; then
    [[ -z "$VM_OR_PID" ]] && usage "VM PID is missing"
    check_int "$VM_OR_PID" 2 || usage "Invalid VM PID provided: must be a positive integer"
    EXE=$( readlink "/proc/$VM_OR_PID/exe" ) || \
        usage "Invalid VM PID provided: no process exists with PID $VM_OR_PID"
    [[ $( grep -Ec '(qemu-system|/usr/bin/kvm)' <<< "$EXE" ) -eq 0 ]] && \
        usage "Invalid VM PID provided: not a VM process ($EXE)"
    sed -e "s/\x00/\n/g" < "/proc/$VM_OR_PID/cmdline" | \
        grep '^-name' -A 1 | \
        tail -n 1 | \
        sed 's/guest=\([^,]*\),.*$/\1/'
else
    [[ -z "$VM_OR_PID" ]] && usage "VM name is missing"
    pgrep -f "guest=$VM_OR_PID,"
fi
