Browse Source

Added error handling function

Matteo Zeccoli Marazzini 5 years ago
parent
commit
e2ba74c8bd
3 changed files with 38 additions and 19 deletions
  1. 17 0
      error.sh
  2. 15 19
      newdisk-automator.sh
  3. 6 0
      parse-arguments.sh

+ 17 - 0
error.sh

@@ -0,0 +1,17 @@
+# arguments errors
+USAGE_E=10
+
+# device errors
+NOTEX_E=1
+NOTBLK_E=2
+ISMOUNT_E=3
+ISSWAP_E=4
+LVMUSED_E=5
+LVMPV_E=6
+
+fatal()
+{
+	STRING=${2:-"generic error"}
+	printf "${PROGRAM_NAME}: error: ${STRING}\n" >&2
+	exit ${1}
+}

+ 15 - 19
newdisk-automator.sh

@@ -1,4 +1,11 @@
-#!/bin/sh
+#!/bin/bash
+
+DIR="/home/ravioli/newdisk-automator"
+
+. "${DIR}/error.sh"
+. "${DIR}/parse-arguments.sh"
+
+PROGRAM_NAME="$0"
 
 DEVICE=$1
 SWAP_SIZE=$2
@@ -6,39 +13,28 @@ CONDOR_SIZE=$3
 TEMP_SIZE=$4
 VM_SIZE=$5
 
-NOTEX_E=1
-NOTBLK_E=2
-ISMOUNT_E=3
-ISSWAP_E=4
-LVMUSED_E=5
-LVMPV_E=5
+fatal 2
 
 # checking if the disk is used
 if [ ! -e ${DEVICE} ] ; then
-	printf "$0: error: ${DEVICE} does not exist.\n" >&2
-	exit ${NOTEX_E}
+	fatal ${NOTEX_E} "${DEVICE} does not exist"
 fi
 if [ ! -b ${DEVICE} ] ; then
-	printf "$0: error: ${DEVICE} is not a block file.\n" >&2
-	exit ${NOTBLK_E}
+	fatal ${NOTBLK_E} "${DEVICE} is not a block file"
 fi
 if grep --quiet "${DEVICE}" /proc/mounts ; then
-	printf "$0: error: ${DEVICE} is mounted. Unmount it first.\n" >&2
-	exit ${ISMOUNT_E}
+	fatal ${ISMOUNT_E} "${DEVICE} is mounted"
 fi
 if grep --quiet "${DEVICE}" /proc/swaps ; then
-	printf "$0: error: ${DEVICE} is used as swap. Swapoff it first.\n" >&2
-	exit ${ISSWAP_E}
+	fatal ${ISSWAP_E} "${DEVICE} is udes as swap"
 fi
 
 if pvs | grep --quiet "${DEVICE}" ; then
 	if [ $(lvs --noheadings --select vg_name="$(pvs --noheadings --select pv_name=~"${DEVICE}" -o vg_name)" --select lv_device_open!=0 | wc -l) -ne 0 ] ; then
-		printf "$0: error: ${DEVICE} is part of a used lvm volume.\n" >&2
-		exit ${LVMUSED_E}
+		fatal ${LVMUSED_E} "${DEVICE} is part of a used lvm volume"
 	fi
 	if [ $(vgs --noheadings --select pv_name=~"${DEVICE}" -o pv_count | uniq) -gt $(vgs --noheadings --select pv_name=~"${DEVICE}" | wc -l) ] ; then
-		printf "$0: error: ${DEVICE} is part of a lvm volume group shared with others physical volumes.\n" >&2
-		exit ${LVMPV_E}
+		fatal ${LVMPV_E} "${DEVICE} is part of a lvm volume group shared with other physical volumes"
 	fi
 
 	# removing lvm and other filesystem signatures)

+ 6 - 0
parse-arguments.sh

@@ -0,0 +1,6 @@
+parse_arguments()
+{
+	if [ $# -lt 1 ] || [ $# -gt 5 ]; then
+		fatal EUSAGE
+	fi
+}