#!/bin/sh /etc/rc.common
# Copyright (C) 2010 OpenWrt.org

START=81

PROG=/usr/sbin/minidlnad
USE_PROCD=1

MINIDLNA_CONFIG_FILE="/var/etc/minidlna.conf"

minidlna_cfg_addbool() {
	local cfg="$1"
	local key="$2"
	local def="$3"
	local val

	config_get_bool val "$cfg" "$key" "$def"
	[ "$val" -gt 0 ] && val="yes" || val="no"
	echo "$key=$val"
}

minidlna_cfg_addstr() {
	local cfg="$1"
	local key="$2"
	local def="$3"
	local val

	config_get val "$cfg" "$key" "$def"
	[ -n "$val" ] && echo "$key=$val"
}

minidlna_cfg_add_media_dir() {
	local val=$1
	echo "media_dir=$val"
}

minidlna_create_config() {
	local cfg=$1
	local port
	local interface

	config_get port "$cfg" port
	config_get interface "$cfg" interface

	{ [ -z "$interface" ] || [ -t "$port" ]; } && return 1

	mkdir -p /var/etc
	echo "# this file is generated automatically, don't edit"

	echo "port=$port"
	echo "network_interface=$interface"

	minidlna_cfg_addstr "$cfg" friendly_name
	minidlna_cfg_addstr "$cfg" user
	minidlna_cfg_addstr "$cfg" db_dir
	minidlna_cfg_addstr "$cfg" log_level 'error'
	minidlna_cfg_addbool "$cfg" inotify '1'
	minidlna_cfg_addbool "$cfg" enable_tivo '0'
	minidlna_cfg_addbool "$cfg" wide_links '0'
	minidlna_cfg_addbool "$cfg" strict_dlna '0'
	minidlna_cfg_addstr "$cfg" album_art_names
	minidlna_cfg_addstr "$cfg" presentation_url
	minidlna_cfg_addstr "$cfg" notify_interval '900'
	minidlna_cfg_addstr "$cfg" serial '12345678'
	minidlna_cfg_addstr "$cfg" model_number '1'
	minidlna_cfg_addstr "$cfg" minissdpsocket
	minidlna_cfg_addstr "$cfg" root_container '.'
	minidlna_cfg_addstr "$cfg" uuid '019f9a56-ff60-44c0-9edc-eae88d09fa05'
	config_list_foreach "$cfg" "media_dir" minidlna_cfg_add_media_dir

	return 0
} > "$MINIDLNA_CONFIG_FILE"

start_service() {
	local enabled
	local db_dir
	local user
	local val

	config_load 'minidlna'
	config_get_bool enabled config 'enabled' '0'

	[ "$enabled" -gt 0 ] || return 1

	config_get val "config" uuid
	[ "$val" = '' ] && uci set minidlna.config.uuid="$(cat /proc/sys/kernel/random/uuid)" && uci commit minidlna

	minidlna_create_config config || return 1

	config_get db_dir config 'db_dir' '/var/run/minidlna'
	config_get user config 'user' 'minidlna'

	[ -d "$db_dir" ] || {
		mkdir -m 755 -p "$db_dir"
		chown -R "$user":"$user" "$db_dir"
	}

	procd_open_instance
	procd_set_param command "$PROG"
	procd_append_param command -S -f "$MINIDLNA_CONFIG_FILE"
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_set_param respawn
	procd_close_instance
}

service_triggers() {
	procd_add_reload_trigger "minidlna"
}
