#!/bin/sh /etc/rc.common
# Copyright (C) 2019 [CTCGFW] Project OpenWRT

. /lib/functions.sh
. /lib/functions/procd.sh

USE_PROCD=1

START=99
STOP=10

init_conf() {
	config_load "filebrowser"
	config_get "addr_type" "config" "addr_type" "lan"
	config_get "db_dir" "config" "db_dir" "/etc"
	[ "${db_dir}" == "/" ] || db_dir="${db_dir%*/}"
	config_get "db_name" "config" "db_name" "filebrowser.db"
	db_name="$(uci get filebrowser.config.db_name| sed 's#/##g')"
	config_get "enabled" "config" "enabled" "0"
	config_get "port" "config" "port" "8989"
	config_get "root_dir" "config" "root_dir" "/"
}

start_service() {
	init_conf
	[ "${enabled}" == "1" ] || exit 0
	procd_open_instance filebrowser
	mkdir -p "${root_dir}"
	mkdir -p "${db_dir}"

	if [ "${addr_type}" == "local" ];then
		addr="127.0.0.1"
	elif [ "${addr_type}" == "lan" ];then
		addr="$(uci get network.lan.ipaddr)"
	elif [ "${addr_type}" == "wan" ];then
		addr="0.0.0.0"
	fi

	procd_set_param command filebrowser
	procd_append_param command -a "${addr}"
	procd_append_param command -d "${db_dir}/${db_name}"
	procd_append_param command -p "${port}"
	procd_append_param command -r "${root_dir}"
	procd_set_param respawn ${respawn_threshold:-3600} ${respawn_timeout:-5} ${respawn_retry:-5}
	procd_close_instance
}

stop_service(){
	init_conf
	echo "${db_dir}/${db_name}" > "/lib/upgrade/keep.d/filebrowser"
}

reload_service()
{
	stop
	start
}

service_triggers() {
        procd_add_reload_trigger "filebrowser"
}
