#!/bin/sh /etc/rc.common
# Copyright (C) 2021 ImmortalWrt

START=90
STOP=10

addr_type="$(uci get filebrowser.config.addr_type)"
db_dir="$(uci get filebrowser.config.db_dir)"
[ "${db_dir}" == "/" ] || db_dir="${db_dir%*/}"
db_name="$(uci get filebrowser.config.db_name| sed 's#/##g')"
enabled="$(uci get filebrowser.config.enabled)"
port="$(uci get filebrowser.config.port)"
root_dir="$(uci get filebrowser.config.root_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

start() {
	stop
	[ "$enabled" == "1" ] || exit 0
	mkdir -p "${root_dir}"
	mkdir -p "${db_dir}"
	filebrowser -a "${addr}" -d "${db_dir}/${db_name}" -p "${port}" -r "${root_dir}" >/dev/null 2>&1 &
}

stop() {
	echo "${db_dir}/${db_name}" > "/lib/upgrade/keep.d/filebrowser"
	killall -3 filebrowser >/dev/null 2>&1
}
