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

POSSIBLE_EXPECTED_STATES=( running paused stopped inactive )

# Auto-complete twik: allow sourcing this file from complete command to get supported args & alias
[[ ${IN_AUTOCOMPLETER:-0} -eq 1 ]] && return

function _vm_state() {
    local vm=$1 hyp=$2 expected_state=$3 state
    if [[ -n "$expected_state" ]]; then
        if in_array "$expected_state" "${POSSIBLE_EXPECTED_STATES[@]}"; then
            if "is_$expected_state" "$vm" "$hyp"; then
                display "The VM $vm is $expected_state on $hyp"
                exit 0
            else
                display "The VM $vm is not $expected_state on $hyp" \
                    "(current state=$( vm_state "$vm" "$hyp" ))"
                exit 1
            fi
        fi
        state=$( vm_state "$vm" "$hyp" )
        if [[ "$state" == "$expected_state" ]]; then
            display "The VM $vm is $expected_state on $hyp"
            exit 0
        else
            display "The VM $vm is not $expected_state on $hyp (current state=$state)"
            exit 1
        fi
        exit 1
    fi
    state=$( vm_state "$vm" "$hyp" )
    display "The VM $vm is $state on $hyp"
}

_simple_command \
    --function _vm_state \
    --short-usage "state [VM] [$(implode '|' "${POSSIBLE_EXPECTED_STATES[@]}")]" \
    "${COMMAND_ARGS[@]:1}" \
    --long-help \
        "Show VM current state" \
        "" \
        "You could specify the expected state of the VM. In this case," \
        "the exit code is based on the test result."
