#!/bin/sh /etc/rc.common

START=99
STOP=00

USE_PROCD=1
PROG=/usr/bin/tvheadend

TEMP_CONFIG=/tmp/tvheadend
PERSISTENT_CONFIG=/etc/tvheadend

execute_first_run() {
	"$PROG" -c "$1" -B -C -A >/dev/null 2>&1
}

ensure_config_exists() {
	local config_path

	config_load tvheadend
	config_get config_path service config_path

	if [ -z "$config_path" ]; then
		[ -d "$PERSISTENT_CONFIG" ] || execute_first_run "$PERSISTENT_CONFIG"
	else
		# if the configuration directory is empty, empty config with grant-all ACL is created
		[ -d "$config_path" ] && [ "$(ls -A $config_path)" ] || execute_first_run "$config_path"
	fi

	# if use_temp_epgdb is enabled (default), most of the config is put to config_path
	# (or /etc/config), except for epgdb.v2, which grows quite large and is write-heavy,
	# so it's put into volatile tmpfs
	# epgdb.v2 is created and symlinked to main config dir upon each start (if it doesn't exist)
	config_get_bool use_temp_epgdb service use_temp_epgdb 1
	if [ "$use_temp_epgdb" == "1" ]; then
		TEMP_EPG="${TEMP_CONFIG}/epgdb.v2"
		[ ! -f "$TEMP_EPG" ] && mkdir -p "$TEMP_CONFIG" && touch "$TEMP_EPG" && chmod 700 "$TEMP_EPG"
		[ -z "$config_path" ] && config_path="$PERSISTENT_CONFIG"
		ln -sf "$TEMP_EPG" "${config_path}/epgdb.v2"
	fi
}

load_uci_config() {
	config_load tvheadend
	config_get config_path service config_path "$PERSISTENT_CONFIG"
	[ -n "$config_path" ] && procd_append_param command -c "$config_path"
	config_get_bool nosyslog service nosyslog 0
	[ "$nosyslog" -eq 1 ] && procd_append_param command --nosyslog
	config_get_bool ipv6 server ipv6 0
	[ "$ipv6" -eq 1 ] && procd_append_param command --ipv6
	config_get bindaddr server bindaddr
	[ -n "$bindaddr" ] && procd_append_param command --bindaddr "$bindaddr"
	config_get http_port server http_port
	[ -n "$http_port" ] && procd_append_param command --http_port "$http_port"
	config_get http_root server http_root
	[ -n "$http_root" ] && procd_append_param command --http_root "$http_root"
	config_get htsp_port server htsp_port
	[ -n "$htsp_port" ] && procd_append_param command --htsp_port "$htsp_port"
	config_get htsp_port2 server htsp_port2
	[ -n "$htsp_port2" ] && procd_append_param command --htsp_port "$htsp_port2"
	config_get xspf server xspf 0
	[ "$xspf" -eq 1 ] && procd_append_param command --xspf
}

start_service() {
	ensure_config_exists
	procd_open_instance
	procd_set_param file /etc/config/tvheadend
	procd_set_param command "$PROG" -B
	load_uci_config
	procd_close_instance
}
