---
version: '3'

tasks:
  clear:
    deps:
      - :install:software:virtualbox
    summary: |
      # Remove All VMs / Reset

      This task will remove all the VirtualBox VMs. It is useful in scenarios
      where VirtualBox is being called through automation and things can
      potentially break. When they break, they need a reset.

      **Example resetting all VMs:**
      `task app:virtualbox:clear`

      There is the capability of only resetting VMs that match a certain pattern.

      **Example resetting all VMs matching a pattern:**
      `task app:virtualbox:clear -- 'macOS'`
    vars:
      DEFAULT_PATTERN: default_
    cmds:
      - cmd: killall -9 VBoxHeadless
        ignore_error: true
      - |
        while read VM; do
          VM_NAME="$(echo $VM | sed 's/^"\(.*\)" {.*}/\1/')"
          VM_UUID="$(echo $VM | sed 's/^".*".{\(.*\)}/\1/')"
          vboxmanage startvm "$VM_UUID" --type emergencystop || true
          vboxmanage unregistervm "$VM_UUID" || true
          rm -rf "$HOME/VirtualBox VMs/$VM_NAME" || true
        done < <(vboxmanage list vms | grep '{{if .CLI_ARGS}}{{.CLI_ARGS}}{{else}}{{.DEFAULT_PATTERN}}{{end}}')