From a3c4bb9b5481681f36aa74778d668622174a594e Mon Sep 17 00:00:00 2001
From: Adar Nimrod <nimrod@shore.co.il>
Date: Wed, 22 Jun 2022 19:30:11 +0300
Subject: [PATCH] Stricter update script and a few fixes.

Check if commands exist and environment.
---
 .bash_completion.d/update |  2 +-
 Documents/bin/update      | 33 +++++++++++++++++++++++++++------
 2 files changed, 28 insertions(+), 7 deletions(-)

diff --git a/.bash_completion.d/update b/.bash_completion.d/update
index 0b89c97..9ca17d1 100644
--- a/.bash_completion.d/update
+++ b/.bash_completion.d/update
@@ -8,7 +8,7 @@ _update() {
     then
         COMPREPLY=($(compgen -W "$opts" -- "$cur"))
     else
-        COMPREPLY=($(compgen -W "all apt flatpak workbench" -- "$cur"))
+        COMPREPLY=($(compgen -W "$(update -l)" -- "$cur"))
     fi
 }
 
diff --git a/Documents/bin/update b/Documents/bin/update
index 62bb92a..c832397 100755
--- a/Documents/bin/update
+++ b/Documents/bin/update
@@ -2,14 +2,24 @@
 set -eu
 
 usage () {
-    echo "Usage: $0 [-d] [all|apt|flatpak|workbench]"
+    echo "Usage: $(basename "$0") [-d] [$(list_supported | tr '\n' '|')]"
 }
 
 header () {
     printf '\n\e[1;92m=== %s ====\e[0m\n\n' "$*" >&2
 }
 
+fail() {
+    printf '\e[1;91m%s\e[0m\n' "$*" >&2
+    exit 1
+}
+
+has() {
+    command -v "$1" >/dev/null 2>&1
+}
+
 _apt () {
+    has apt-get || fail apt-get not found.
     header Updating APT
     if [ -n "${DOWNLOAD_ONLY:-}" ]
     then
@@ -20,6 +30,7 @@ _apt () {
 }
 
 _flatpak() {
+    has flatpak || fail flatpak not found.
     header Updating Flatpak
     flatpak --system update --appstream
 
@@ -33,6 +44,8 @@ _flatpak() {
 }
 
 _workbench() {
+    has wb || fail wb not found.
+    ! wb -i || fail Cannot update the workbench container from inside the workbench container.
     header Updating Workbench
     if [ -n "${DOWNLOAD_ONLY:-}" ]
     then
@@ -43,16 +56,24 @@ _workbench() {
 }
 
 _all() {
-    _apt
-    _flatpak
-    _workbench
+    ! has apt-get || _apt
+    ! has flatpak || _flatpak
+    ! { has wb || wb -i; } || _workbench
+}
+
+list_supported() {
+    ! has apt-get || echo apt
+    ! has flatpak || echo flatpak
+    ! has wb || wb -i || echo workbench
+    printf '%s' all
 }
 
-while getopts 'dh' opt
+while getopts 'dhl' opt
 do
     case "$opt" in
         d) DOWNLOAD_ONLY=1;;
-        h) usage;;
+        h) usage; exit;;
+        l) list_supported; exit;;
         *) usage; exit 1;;
     esac
 done
-- 
GitLab