# Tiny Cloud - common script functions
# vim:set filetype=sh:
# shellcheck shell=sh

# set defaults
[ -f "$ROOT/etc/tiny-cloud.conf" ] && . "$ROOT/etc/tiny-cloud.conf"
: "${CLOUD:=unknown}"
: "${CLOUD_USER:=alpine}"
: "${TINY_CLOUD_LOGS:=$ROOT/var/log}"
: "${TINY_CLOUD_VAR:=$ROOT/var/lib/cloud}"

log() {
	local facility="local7"
	local stderr init
	local tag=$(basename "$0")
	while [ "${1#-}" != "$1" ]; do
		case "$1" in
			-i) init=1 ;;
			-f) facility="$2"; shift ;;
			-s) stderr=-s ;;
			-t) tag="$tag/$2"; shift ;;
		esac
		shift
	done
	local level="$1"
	[ -z "$DEBUG" ] && [ "$level" = debug ] && return
	shift

	[ -n "$init" ] && echo "$@" >&2
	logger $stderr -p "$facility.$level" -t "${tag}[$$]" -- "$@"
	case "$level" in
		crit|alert|emerg) exit 1 ;;
	esac
}

# usage: replace_word <search> <replace> <list>...
replace_word() {
	local search="$1" replace="$2"
	shift 2
	for word in "$@"; do
		if [ "$word" = "$search" ]; then
			echo "$replace"
		else
			echo "$word"
		fi
	done
}

# usage: insert_after <where> <what> <list>...
insert_before() {
	local search="$1" addition="$2"
	shift 2
	for i in "$@"; do
		if [ "$i" = "$search" ]; then
			echo "$addition"
		fi
		echo "$i"
	done
}

# usage: insert_after <where> <what> <list>...
insert_after() {
	local search="$1" addition="$2"
	shift 2
	for i in "$@"; do
		echo "$i"
		if [ "$i" = "$search" ]; then
			echo "$addition"
		fi
	done
}

# usage: add_once <file> <line-to-add>...
add_once() {
	local file="$1"
	shift
	for line; do
		if ! grep -x -F "$line" "$file" 2>/dev/null; then
			mkdir -p "${file%/*}"
			printf "%s\n" "$line" >> "$file"
		fi
	done
}
