#!/bin/sh /etc/rc.common
# Copyright (C) 2018-2020 Lienol <lawlienol@gmail.com>

START=99

LOG_PATH="/var/log/filebrowser.log"

echolog() {
	echo -e "$(date "+%Y-%m-%d %H:%M:%S"): $1" >> $LOG_PATH
}

config_t_get() {
	local index=0
	[ -n "$4" ] && index=$4
	local ret=$(uci get filebrowser.@$1[$index].$2 2>/dev/null)
	echo ${ret:=$3}
}
start() {
	ENABLED=$(config_t_get global enable 0)
	[ "$ENABLED" = "0" ] && return
	PORT=$(config_t_get global port 8088)
	ROOT_PATH=$(config_t_get global root_path /)
	project_directory=$(config_t_get global project_directory /tmp)
	[ ! -f "$project_directory/filebrowser" ] && echolog "在$project_directory找不到FileBrowser主程序，请下载。" && exit
	export HOME="/root"
	$project_directory/filebrowser -a 0.0.0.0 -p $PORT -r $ROOT_PATH -d ${ROOT_PATH}filebrowser.db -l $LOG_PATH >/dev/null 2>&1 &
}

stop() {
	ps -w | grep -v "grep" | grep "$project_directory/filebrowser -a 0.0.0.0" | awk '{print $1}' | xargs kill -9 >/dev/null 2>&1 &
	rm -rf $LOG_PATH
}

restart() {
	stop
	sleep 1
	start
}