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

START=90
STOP=10
USE_PROCD=1
NAME=mediamtx

CONF_FILE="/var/etc/mediamtx.yml"

# Append a line to the generated YAML config
yaml() {
	echo "$1" >> "$CONF_FILE"
}

# Convert UCI bool (0/1) to YAML bool (no/yes)
uci_bool() {
	[ "$1" = "1" ] && echo "yes" || echo "no"
}

generate_global() {
	local log_level log_destination udp_max_payload_size
	local write_queue_size read_timeout write_timeout udp_push

	config_get log_level global log_level 'warn'
	config_get log_destination global log_destination 'syslog'
	config_get udp_max_payload_size global udp_max_payload_size '1368'
	config_get write_queue_size global write_queue_size '512'
	config_get read_timeout global read_timeout '10s'
	config_get write_timeout global write_timeout '10s'
	config_get_bool udp_push global udp_push 0

	yaml "logLevel: $log_level"
	yaml "logDestinations: [$log_destination]"
	yaml "udpMaxPayloadSize: $udp_max_payload_size"
	yaml "writeQueueSize: $write_queue_size"
	yaml "readTimeout: $read_timeout"
	yaml "writeTimeout: $write_timeout"
	yaml "udpPush: $(uci_bool $udp_push)"
}

generate_protocol() {
	local section="$1"
	local enabled address

	config_get_bool enabled "$section" enabled 0
	config_get address "$section" address ''

	case "$section" in
		rtsp)
			yaml ""
			yaml "rtsp: $(uci_bool $enabled)"
			[ -n "$address" ] && yaml "rtspAddress: $address"
			local protocols=""
			append_rtsp_proto() { protocols="${protocols:+$protocols, }$1"; }
			config_list_foreach "$section" protocol append_rtsp_proto
			[ -n "$protocols" ] && yaml "protocols: [$protocols]"
			;;
		rtmp)
			yaml ""
			yaml "rtmp: $(uci_bool $enabled)"
			[ -n "$address" ] && yaml "rtmpAddress: $address"
			;;
		hls)
			local variant segment_count segment_duration always_remux

			config_get variant "$section" variant 'lowLatency'
			config_get segment_count "$section" segment_count '7'
			config_get segment_duration "$section" segment_duration '1s'
			config_get_bool always_remux "$section" always_remux 0

			yaml ""
			yaml "hls: $(uci_bool $enabled)"
			[ -n "$address" ] && yaml "hlsAddress: $address"
			yaml "hlsVariant: $variant"
			yaml "hlsSegmentCount: $segment_count"
			yaml "hlsSegmentDuration: $segment_duration"
			yaml "hlsAlwaysRemux: $(uci_bool $always_remux)"
			;;
		webrtc)
			local udp_address
			config_get udp_address "$section" udp_address ':8189'

			yaml ""
			yaml "webrtc: $(uci_bool $enabled)"
			[ -n "$address" ] && yaml "webrtcAddress: $address"
			yaml "webrtcLocalUDPAddress: $udp_address"
			;;
		srt)
			yaml ""
			yaml "srt: $(uci_bool $enabled)"
			[ -n "$address" ] && yaml "srtAddress: $address"
			;;
	esac
}

generate_api() {
	local enabled address

	config_get_bool enabled api enabled 0
	config_get address api address ':9997'

	yaml ""
	yaml "api: $(uci_bool $enabled)"
	yaml "apiAddress: $address"
}

generate_path() {
	local section="$1"
	local enabled name source source_on_demand max_readers rtsp_any_port
	local rtsp_source_protocol outgoing_rtp_url outgoing_rtp_mtu

	config_get_bool enabled "$section" enabled 1
	[ "$enabled" -eq 0 ] && return

	config_get name "$section" name "$section"
	config_get source "$section" source 'publisher'
	config_get_bool source_on_demand "$section" source_on_demand 0
	config_get max_readers "$section" max_readers '0'
	config_get_bool rtsp_any_port "$section" rtsp_any_port 1
	config_get rtsp_source_protocol "$section" rtsp_source_protocol 'udp'
	config_get outgoing_rtp_url "$section" outgoing_rtp_url ''
	config_get outgoing_rtp_mtu "$section" outgoing_rtp_mtu '1472'

	yaml "  $name:"
	yaml "    source: $source"
	yaml "    sourceOnDemand: $(uci_bool $source_on_demand)"
	yaml "    maxReaders: $max_readers"
	yaml "    rtspAnyPort: $(uci_bool $rtsp_any_port)"
	yaml "    sourceProtocol: $rtsp_source_protocol"
	[ -n "$outgoing_rtp_url" ] && yaml "    outgoingRTPURL: $outgoing_rtp_url"
	yaml "    outgoingRTPMTU: $outgoing_rtp_mtu"
}

generate_paths() {
	yaml ""
	yaml "paths:"
	config_foreach generate_path path
}

start_service() {
	local global_enabled

	config_load mediamtx

	config_get_bool global_enabled global enabled 1
	if [ "$global_enabled" -eq 0 ]; then
		logger -p warn -t "$NAME" "Service disabled"
		return
	fi

	mkdir -p "$(dirname "$CONF_FILE")"
	echo "# Auto-generated from /etc/config/mediamtx — do not edit" > "$CONF_FILE"

	generate_global
	generate_protocol rtsp
	generate_protocol rtmp
	generate_protocol hls
	generate_protocol webrtc
	generate_protocol srt
	generate_api
	generate_paths

	# Explicitly disable unused features
	yaml ""
	yaml "record: no"
	yaml "playback: no"
	yaml "metrics: no"
	yaml "pprof: no"

	procd_open_instance
	procd_set_param command /usr/bin/mediamtx "$CONF_FILE"
	procd_set_param respawn
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_set_param file /etc/config/mediamtx
	procd_close_instance

	logger -p notice -t "$NAME" "Started with config $CONF_FILE"
}

stop_service() {
	logger -p notice -t "$NAME" "Stopped"
}

service_triggers() {
	procd_add_reload_trigger "$NAME"
}
