#!/bin/sh
#### Set features from nvram to features.conf

HOST_FEATURES_CONF="${MEDIACASTER_DIR}/etc/features.conf"

# Retrieve a setting from nvconfig
get_nvconfig () {
	CONFIG_NAME="$1"
	CONFIG_VALUE=$(nvconfig get "${CONFIG_NAME}")

	if [ "${CONFIG_VALUE}" == "" ]; then
		return 1
	fi

	echo "${CONFIG_VALUE}"

	return 0
}

# Apply a setting to nvconfig
set_nvconfig() {
	CONFIG_NAME="$1"
	CONFIG_VALUE="$2"
	nvconfig set "${CONFIG_NAME}" "${CONFIG_VALUE}"
}

# Apply a setting to HOST_FEATURES_CONF
set_feature () {
	FEATURE_NAME="$1"
	FEATURE_VALUE="$2"

	# Update HOST_FEATURES_CONF
	sed -i "/^${FEATURE_NAME}=/d" ${HOST_FEATURES_CONF}
	echo "${FEATURE_NAME}=${FEATURE_VALUE}" >> ${HOST_FEATURES_CONF}
}

# Copy an nvconfig variable to features.conf, or use the default and set in nvconfig
apply () {
	CONFIG_NAME="$1"
	FEATURE_NAME="$2"
	DEFAULT_VALUE="$3"

	CONFIG_VALUE=$(get_nvconfig "${CONFIG_NAME}")
	if [ "$CONFIG_VALUE" == "" ]; then
		CONFIG_VALUE="${DEFAULT_VALUE}"
		if [ "$DEFAULT_VALUE" != "" ]; then
			set_nvconfig "${CONFIG_NAME}" "${CONFIG_VALUE}"
		fi
	fi

	if [ "$CONFIG_VALUE" != "" ]; then
		set_feature "${FEATURE_NAME}" "${CONFIG_VALUE}"
		return 0
	fi

	return 1
}

#### Retrieve the UDID or user a generated one if not set
HIPPLAY_DEVICE_ID=$(cat /proc/sys/kernel/random/uuid)
apply "Hipplay_device_id"      "Hipplay_device_id"          "${HIPPLAY_DEVICE_ID}"

#### Filesystem watcher configuration
apply "DB2CS_Ignore_Time"      "INOTIFY_IGNORE_TIME"
apply "DB2CS_Max_Ignore_Time"  "INOTIFY_MAX_IGNORE_TIME"
apply "DB2CS_Poll_Time"        "INOTIFY_POLL_TIME"
apply "DB2CS_Notification_URL" "NOTIFICATION_URL"
