#! /bin/bash

set -o errexit
set -o pipefail
shopt -s extglob

helptext() {
    cat <<'EOF'
Usage: bashtemplate [-b] [-h] [-s string] [-x number] first second

Template file with a bunch of arbitrary settings to use for templating scripts.

-b
    Set a boolean value to true.
-h
    Print this message and exit.
-s name
    Set a string value to "name".
-x number
    Set a value for arithmetic operations to "number".
EOF
    exit $1
}

check_number() {
    if [[ "$1" != +([0-9]) ]]; then
        echo >&2 'X must be an integer equal to or greater than zero.'
        exit 1
    fi
    echo $1
}

BOOLEAN=''
NAME=''
X=0

while getopts bhs:x: option; do
    case $option in
        (b) BOOLEAN=TRUE;;
        (h) helptext 0;;
        (s) NAME="$OPTARG";;
        (x) X=$(check_number "$OPTARG");;
        (*) helptext >&2 1;;
    esac
done

shift $(( OPTIND - 1 ))

if [[ $# -ne 2 ]]; then
    helptext >&2 1
fi

FIRST="$1"
SECOND="$2"

TRAPZERR() {
    if [[ -v WORKFILE && -f "$WORKFILE" ]]; then
        rm -f "$WORKFILE"
    fi
}

trap TRAPZERR ERR

WORKFILE="$(mktemp)"

echo First is "$FIRST"
echo Second is "$SECOND"

if [[ -n "$BOOLEAN" ]] && (( X > 0 )); then
    echo Boolean is set and X is larger than 0.
fi

if [[ -z "$BOOLEAN" ]]; then
    echo Boolean is false.
fi

echo X is "$X"

if [[ -n "$NAME" ]]; then
    echo Hello, "$NAME".
fi

rm "$WORKFILE"