From 0c75a4053e8b467057a5a52101d7c07e6ba1b015 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Nicolas=20=E2=80=9CNiols=E2=80=9D=20Jeannerod?=
 <nicolas.jeannerod@moduscreate.com>
Date: Wed, 26 Feb 2025 12:47:48 +0100
Subject: [PATCH] Report already deleted VM in a clean way

---
 infra/proxmox-remove.sh | 29 ++++++++++++++++++++++++++---
 1 file changed, 26 insertions(+), 3 deletions(-)

diff --git a/infra/proxmox-remove.sh b/infra/proxmox-remove.sh
index 1d2b046..94d66d5 100755
--- a/infra/proxmox-remove.sh
+++ b/infra/proxmox-remove.sh
@@ -111,9 +111,17 @@ proxmox () {
   release_lock proxmox
 }
 
+## Way to inject different behaviour on unexpected status.
+default_proxmox_sync_unexpected_status_handler () {
+  die "unexpected status: '%s'" "$1"
+}
+proxmox_sync_unexpected_status_handler=default_proxmox_sync_unexpected_status_handler
+
 ## Synchronous variant for when the `proxmox` function would just respond an
 ## UPID in the `data` JSON field.
-proxmox_sync () (
+proxmox_sync () {
+  local response upid status
+
   response=$(proxmox "$@")
   upid=$(echo "$response" | jq -r .data)
 
@@ -124,10 +132,10 @@ proxmox_sync () (
     case $status in
       running) sleep 1 ;;
       stopped) break ;;
-      *) die "unexpected status: '%s'" "$status" ;;
+      *) "$proxmox_sync_unexpected_status_handler" "$status" ;;
     esac
   done
-)
+}
 
 ################################################################################
 ## Grab VM options
@@ -186,12 +194,27 @@ stop_vm () {
 ################################################################################
 ## Delete VM
 
+proxmox_sync_unexpected_status_handler_ignore_null () {
+  case $1 in
+    null)
+      printf "Attempted to delete VM %s, but got 'null' status. Maybe the VM already does not exist?\n" \
+        "$vm_name"
+      exit 0
+      ;;
+    *)
+      default_proxmox_sync_unexpected_status_handler "$1"
+      ;;
+  esac
+}
+
 delete_vm () {
   printf 'Deleting VM %s...\n' "$vm_name"
 
+  proxmox_sync_unexpected_status_handler=proxmox_sync_unexpected_status_handler_ignore_null
   proxmox_sync DELETE "$api_url/nodes/$node/qemu/$vm_id" \
     'destroy-unreferenced-disks'==1 \
     'purge'==1
+  proxmox_sync_unexpected_status_handler=default_proxmox_sync_unexpected_status_handler
 
   printf 'done deleting VM %s.\n' "$vm_name"
 }