changeset 5936:a9c75430cb26

mod_rest: use bash getopts to handle cli flags in example script
author Kim Alvefur <zash@zash.se>
date Sun, 21 Jul 2024 17:58:41 +0200
parents 46394b327d17
children da942a3f3660
files mod_rest/example/rest.sh
diffstat 1 files changed, 38 insertions(+), 13 deletions(-) [+]
line wrap: on
line diff
--- a/mod_rest/example/rest.sh	Mon Jul 15 20:02:25 2024 +0200
+++ b/mod_rest/example/rest.sh	Sun Jul 21 17:58:41 2024 +0200
@@ -9,6 +9,12 @@
 
 # shellcheck disable=SC1091
 
+SELF="${0##*/}"
+function usage() {
+	echo "${SELF} [-h HOST] [-rw] [/path] kind=(message|presence|iq) ...."
+	# Last arguments are handed to HTTPie, so refer to its docs for further details
+}
+
 # Settings
 HOST=""
 DOMAIN=""
@@ -25,24 +31,43 @@
 fi
 
 if [[ $# == 0 ]]; then
-	echo "${0##*/} [-h HOST] [-rw] [/path] kind=(message|presence|iq) ...."
-	# Last arguments are handed to HTTPie, so refer to its docs for further details
-	exit 0
+	usage
+	exit 1
 fi
 
-if [[ "$1" == "-h" ]]; then
-	HOST="$2"
-	shift 2
-elif [ -z "${HOST:-}" ]; then
+while getopts 'r:h:' flag; do
+	case "$flag" in
+		r)
+			case "$OPTARG" in
+				o)
+					# Default
+					SESSION="session-read-only"
+					;;
+				w)
+					# To e.g. save Accept headers to the session
+					SESSION="session"
+					;;
+				*)
+					echo "E: -ro OR -rw" >&2
+					exit 1
+					;;
+			esac
+			;;
+		h)
+			HOST="$OPTARG"
+			;;
+		*)
+			echo "E: Unknown flag '$flag'" >&2
+			usage >&2
+			exit 1
+	esac
+done
+shift $((OPTIND-1))
+
+if [ -z "${HOST:-}" ]; then
 	HOST="$(hostname)"
 fi
 
-if [[ "$1" == "-rw" ]]; then
-	# To e.g. save Accept headers to the session
-	SESSION="session"
-	shift 1
-fi
-
 if [[ "$HOST" != *.* ]]; then
 	# Assumes subdomain of your DOMAIN
 	if [ -z "${DOMAIN:-}" ]; then