#!/bin/sh -e

vmname="$1"

if echo "$vmname" | grep -vqE '^(cvm|capsul)-[a-z0-9]{10}$'; then
  echo "vmname $vmname must match "'"^capsul-[a-z0-9]{10}$"'
  exit 1
fi

# this will let us know if the vm exists or not
exists="false"
state="unknown"
if virsh domuuid "$vmname" | grep -vqE '^[\t\s\n]*$'; then
  exists="true"

  state_code="$(virsh domstats $vmname | grep state.state | cut -d '=' -f 2)"

  if printf "$state_code\n" | grep -vqE '^[0-8]$'; then
    printf 'state_code was not detected. state_code %s must match ^[0-8]$\n' "$state_code"
    exit 1
  fi

  case "$state_code" in
    1) state="running" ;;
    2) state="blocked" ;;
    4) state="stopping" ;;
    6) state="crashed" ;;
    [357]) state="stopped" ;;
  esac
fi

# this gets the ipv4
ipv4="$(virsh domifaddr "$vmname" | awk '/ipv4/ {print $4}' | cut -d'/' -f1)"

echo "$exists $state $ipv4"