#!/bin/sh

ASTERISK_DIR="/etc/asterisk"

read_sys_value() {
	local path="$1"

	[ -r "$path" ] || return 1
	tr -d '\000' < "$path" 2>/dev/null
}

get_model() {
	local model

	model="$(read_sys_value /sys/mnf_info/name)"
	[ -n "$model" ] || return 1
	# All supported devices use the first 6 characters as the model code.
	model="$(printf '%.6s' "$model")"
	# Sanitize: the model code is used as a path component in
	# copy_tree "$TEMPLATE_ROOT/$FAMILY/$MODEL". Reject anything that
	# isn't a plain alphanumeric token so a malformed mnf_info value
	# can't traverse outside the template tree.
	case "$model" in
		*[!A-Za-z0-9]*|"")
			return 1
			;;
	esac
	printf '%s\n' "$model"
}

get_platform() {
	local platform

	platform="$(read_sys_value /proc/device-tree/platform)"
	[ -n "$platform" ] || return 1
	echo "$platform"
}

map_family() {
	case "$1" in
	TEG100*)
		echo "teg100"
		;;
	RUTX*|ATRM50*)
		echo "rutx"
		;;
	*)
		return 1
		;;
	esac
}

copy_tree() {
	local dir="$1"
	local rel

	[ -d "$dir" ] || return 0

	mkdir -p "$ASTERISK_DIR"
	(
		cd "$dir" || exit 1
		find . -type f
	) | while IFS= read -r rel; do
		rel="${rel#./}"
		mkdir -p "$ASTERISK_DIR/$(dirname "$rel")"
		cp "$dir/$rel" "$ASTERISK_DIR/$rel"
		chmod 0644 "$ASTERISK_DIR/$rel"
	done
}

copy_uci_seed() {
	local src="$1"

	[ -f "$src" ] || return 0
	cp "$src" /etc/config/asterisk
	chmod 0644 /etc/config/asterisk
}

MODEL="$(get_model 2>/dev/null)"
PLATFORM="$(get_platform 2>/dev/null)"
FAMILY="$(map_family "$PLATFORM" 2>/dev/null)" || exit 0

# Templates install under /usr/local (the writable overlay) when the package is
# added via opkg on a read-only-rootfs device, or under /usr when baked into the
# image. Pick whichever exists, mirroring $PATH precedence.
for TEMPLATE_ROOT in /usr/local/usr/share/asterisk-config /usr/share/asterisk-config; do
	[ -d "$TEMPLATE_ROOT" ] && break
done

copy_tree "$TEMPLATE_ROOT/$FAMILY/default"
copy_tree "$TEMPLATE_ROOT/$FAMILY/$MODEL"

copy_uci_seed "$TEMPLATE_ROOT/uci/$FAMILY/asterisk"

# Pre-render trunk config so the first asterisk boot already has
# /etc/asterisk/{pjsip,extensions}_trunks.conf in place. Resolve via $PATH
# so it works whether the binary is under /usr/local or /usr.
command -v asterisk-uci-gen >/dev/null 2>&1 && asterisk-uci-gen || true

exit 0
