# Script UserData Functions
# vim:set filetype=sh:
# shellcheck shell=sh

init__run_userdata() {
	local log="$TINY_CLOUD_LOGS/tiny-cloud-scripts.log"
	local exit="$TINY_CLOUD_LOGS/tiny-cloud-scripts.exit"
	local scripts="$TINY_CLOUD_VAR/scripts"
	local name userdata rv

	make_file "$log" || return
	: > "$log"
	rm -f "$exit"
	set -- "$scripts"
	if [ -d "$scripts" ]; then
		make_dir "$scripts" || return
		set -- "$scripts/"*
	fi
	for userdata; do
		[ -f "$userdata" ] || continue
		name="${userdata##*/}"
		printf '=== script %s started ===\n' "$name" | tee -a "$log"
		perms set "$userdata" || return
		{
			if "$userdata"; then
				make_file "$exit" && echo 0 > "$exit"
			else
				rv=$?
				make_file "$exit" && echo "$rv" > "$exit"
			fi
		} 2>& 1 | tee -a "$log"
		rv=$(cat "$exit")
		printf '\n=== script %s finished with exit %s ===\n' \
			"$name" "$rv" | tee -a "$log"
		[ "$rv" -eq 0 ] || return "$rv"
	done

	return 0
}

handler__organize_userdata() (
	local source="$1" scripts="$TINY_CLOUD_VAR/scripts"
	local name number=0 target tmpfile value

	make_dir "$scripts" || return
	for target in "$scripts/"*; do
		[ -f "$target" ] || continue
		name="${target##*/}"
		case "$name" in *[!0-9]*|'') continue;; esac
		value=$(printf "%s" "$name" | sed 's/^0*//')
		: "${value:=0}"
		[ "$value" -gt "$number" ] && number="$value"
	done
	number=$((number + 1))
	target=$(printf "%s/%04d" "$scripts" "$number")
	tmpfile=$(mktemp "$target.XXXXXX") || return
	trap 'rm -f "$tmpfile"' 0
	trap 'exit 1' HUP INT TERM
	cat "$source" > "$tmpfile" && perms set "$tmpfile" "$target" && mv "$tmpfile" "$target"
)

# add init actions
INIT_ACTIONS_FINAL="${INIT_ACTIONS_FINAL} run_userdata"
