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

START=99
BIN=/usr/sbin/owntone
PID=/var/run/owntone.pid
SSD=start-stop-daemon

NAME=owntone

uci_get_by_name() {
	local ret=$(uci get $NAME.$1.$2 2>/dev/null)
	echo ${ret:=$3}
}

uci_get_by_type() {
	local ret=$(uci get $NAME.@$1[0].$2 2>/dev/null)
	echo ${ret:=$3}
}

gen_config_file() {
cat <<-EOF >/var/etc/owntone.conf
general {
	uid = "root"
	db_path = "$(uci_get_by_type owntone db_path)"
	logfile = "/var/log/owntone.log"
	loglevel = log
	ipv6 = no
	cache_path = "/var/owntone-cache.db"
}

library {
	name = "My Music on OpenWrt"
	port = $(uci_get_by_type owntone port 3689)
	directories = { "$(uci_get_by_type owntone directories)" }
	podcasts = { "/Podcasts" }
	audiobooks = { "/Audiobooks" }
	compilations = { "/Compilations" }
	compilation_artist = "Various Artists"
}

audio {
	nickname = "Local Audio Output"
	type = "alsa"
}
EOF
}

start() {
        gen_config_file
        local enabled=$(uci_get_by_type owntone enabled 0)
        [ "$enabled" == "0" ] && return 1
        $SSD -p $PID -S -b -x $BIN -- -P $PID -c /var/etc/owntone.conf
}
	
stop() {
        $SSD -p $PID -K -s SIGINT >/dev/null
}

restart() {
        stop
        sleep 3
        start
}
