From e082f4048b15142dcb4114355baa0647bae51183 Mon Sep 17 00:00:00 2001
From: Massimiliano Adamo <massimiliano.adamo@geant.org>
Date: Thu, 3 Jun 2021 22:39:57 +0200
Subject: [PATCH] add check version to shell script

---
 acme-downloader.sh | 42 +++++++++++++++++++++++++++++++-----------
 1 file changed, 31 insertions(+), 11 deletions(-)

diff --git a/acme-downloader.sh b/acme-downloader.sh
index f2ea20b..225ad19 100755
--- a/acme-downloader.sh
+++ b/acme-downloader.sh
@@ -7,15 +7,6 @@
 # the certificate will be checked, if it is valid, if the key matches
 # and if it contains at least the cert-name
 #
-LOCAL_MD5=$(md5sum $0 | awk '{print $1}')
-SCRIPT_URL="https://artifactory.software.geant.org/artifactory/acme-downloader/acme-downloader.sh"
-REMOTE_MD5=$(curl -s $SCRIPT_URL | md5sum | awk '{print $1}')
-if [[ $LOCAL_MD5 != $REMOTE_MD5 ]]; then
-    echo "$0 differs from $SCRIPT_URL"
-    echo "suggesting that you are running an older version"
-    echo ""
-fi
-
 REDIS_URL="https://redis.geant.org/GET"
 VAULT_URL="https://vault.geant.org/v1"
 TMP_CERT=$(mktemp)
@@ -38,11 +29,35 @@ trap 'clean_up' SIGINT
 if [ $(id -u) -ne 0 ]; then
     echo -e "plase run this script as root\ngiving up..."
     clean_up 2
-elif ! which curl jq &>/dev/null; then
-    echo -e "please install curl and jq\ngiving up..."
+elif ! which jq &>/dev/null; then
+    echo -e "please install jq\ngiving up..."
+    clean_up 2
+elif ! which curl &>/dev/null; then
+    echo -e "please install curl\ngiving up..."
     clean_up 2
 fi
 
+check_version() {
+    # check upstrem version
+    LOCAL_MD5=$(md5sum $1 | awk '{print $1}')
+    SCRIPT_URL="https://artifactory.software.geant.org/artifactory/acme-downloader/acme-downloader.sh"
+    METADATA_URL="https://artifactory.software.geant.org/artifactory/api/storage/acme-downloader/acme-downloader.sh"
+    REMOTE_MD5=$(curl -s $METADATA_URL | jq -j .checksums.md5)
+    if [[ $LOCAL_MD5 != $REMOTE_MD5 ]]; then
+        echo "$1 differs from $SCRIPT_URL"
+        echo "suggesting that you are running an older version"
+        echo "in order to fetch and install the new version you can use the option: --update"
+        echo ""
+    else
+        if [ -n $CHECK ]; then
+            echo "you are running the latest version"
+        fi
+    fi
+    if [ -n $CHECK ]; then
+        exit 0
+    fi
+}
+
 # lsb_release is not always installed
 if ! source /etc/os-release &>/dev/null; then
     echo "no idea what to do with this OS: I was not able to access /etc/os-release"
@@ -136,6 +151,9 @@ while true; do
     --update)
         UPDATE='UPDATE'
         ;;
+    --check-version)
+        CHECK='CHECK'
+        ;;
     --)
         shift
         break
@@ -146,6 +164,8 @@ done
 
 TYPE=$(echo $TYPE | tr '[:lower:]' '[:upper:]')
 
+check_version $0
+
 if [ -n $UPDATE ]; then
     curl $SCRIPT_URL -o $0
     UPDATE_STATUS=$?
-- 
GitLab