# Shared functions

### General variables
ERROR=""

### Check if string is alpha
function isalpha {
	case "$*" in
		([!a-zA-Z]*)	return 1;;
		(*)		return 0;;
	esac
}

### Check if string is alphanum
function isalphanum {
	local str="$*"
	if [ -n "$str" ]; then
		return 1
	fi
	case "$str" in
		([!a-zA-Z0-9]*)	return 1;;
		(*)		return 0;;
	esac
}

### Check if string is allowed veriablename
function isvarname {
	case "$*" in
		([!a-zA-Z0-9_]*)	return 1;;
		(*)			return 0;;
	esac
}

### Check if string is numerical
function isnum {
	case "$*" in
		(![0-9]*)	return 1;;
		(*)		return 0;;
	esac
}

### Give a timestamp
function timestamp {
	echo $(date +'%h %d %H:%M:%S')
}

### Just log and fill error-buffer
function log {
#	local msg="$(timestamp) $GROUP/$SERVERNAME $*"
	local msg=""

	echo "$msg: $*" >&2
	ERRORBUFFER="$ERRORBUFFER\n$msg: $*"
}

### Log only if debugging is on
function debug {
	if [ "$DEBUG" == "yes" ]; then
		log "DEBUG: $*"
	else
		local MSG="$(timestamp) $*"
		ERRORBUFFER="$ERRORBUFFER\n$MSG"
	fi
}

### Log and put error-boolean on (so die will escalate the problem)
function error {
	ERROR="yes"
	function="$1"
	lineno="$2"
	shift 2

	log "ERROR: $function[$lineno]: $*"
}

### Stop running and escalate if problems
function die {
	if [ "$*" -o "$ERROR" == "yes" ]; then
		ERROR="yes"
		log "$* Exiting."
		exit 1
	else
		debug "Exiting successfully."
		exit 0
	fi
}

### Main
if [ -r "$DWALLCONFIG" ]; then
	source "$DWALLCONFIG"
else
	die "Cannot access configfile ($DWALLCONFIG)."
fi
