#!/usr/bin/env bash
set -eu

function GetDomains() {
  if [ "${1:?}" == "suspend" ]; then
    "/opt/apps/xcb-base/bin/xcb-virsh" list --state-running --uuid 2>/dev/null || true
  elif [ "${1:?}" == "resume" ]; then
    "/opt/apps/xcb-base/bin/xcb-virsh" list --state-paused --uuid 2>/dev/null || true
  fi
}

function GetDomainName() {
  "/opt/apps/xcb-base/bin/xcb-virsh" domname "${1:?}" || echo "${1:?}"
}

function HandleDomains() {
  local -i _COUNT
  local _DOMAINS _DOMAIN _OUTPUT
  _COUNT=0
  _DOMAINS="$(GetDomains "${1:?}")"
  while IFS= read -r _DOMAIN; do
    if [ "${_DOMAIN}" != "" ]; then
      if _OUTPUT=$("/opt/apps/xcb-base/bin/xcb-virsh" "${1:?}" "${_DOMAIN}"); then
        if [ "${1:?}" == "resume" ]; then
          "/opt/apps/xcb-base/bin/xcb-virsh" domtime "${_DOMAIN}" --now || true
        fi
        echo "XCB Domain: $(GetDomainName "${_DOMAIN}") ${1:?} is success."
      else
        echo "XCB Domain: $(GetDomainName "${_DOMAIN}") ${1:?} is failure, ${_OUTPUT}" >&2
      fi
    fi
  done <<<"${_DOMAINS}"
}

if [ "${1:-}" == "start" ]; then
  HandleDomains "suspend"
elif [ "${1:-}" == "stop" ]; then
  HandleDomains "resume"
fi
