#!/bin/sh /etc/rc.common
#
# Copyright (C) 2021-2022  sirpdboy  <herboy2008@gmail.com> https://github.com/sirpdboy/luci-app-lucky

# This file is part of lucky .
#
# This is free software, licensed under the Apache License, Version 2.0 .


USE_PROCD=1
START=99
STOP=10

CONF="lucky"
PROG=/usr/bin/lucky
LUCKYDIR=/etc/lucky
LUCKYCONF=/etc/lucky/lucky.conf

get_config() {
  config_get_bool enabled $1 enabled 1
	config_get_bool logger $1 logger 1
	config_get port $1 port 16601
	config_get AllowInternetaccess $1 AllowInternetaccess 0
}

lucky_prepare() {
	pgrep -f $PROG | xargs kill -9 >/dev/null 2>&1 
}


start_service() {
	stop_service
	config_load "$CONF"
	config_foreach get_config "$CONF"

	[ "x$enabled" = "x1" ] || return 1
	if [ "x$AllowInternetaccess" = "x1" ] ;then
		sed -i 's/"AllowInternetaccess": false,/"AllowInternetaccess": true,/g' "$LUCKYCONF"
	else
		sed -i 's/"AllowInternetaccess": true,/"AllowInternetaccess": false,/g' "$LUCKYCONF"
	fi
	# set_firewall
	procd_open_instance
	procd_set_param command "$PROG"
	procd_append_param command -c "$LUCKYCONF" -p $port
	[ "x$logger" == x1 ] && procd_set_param stderr 1
	procd_set_param respawn
	procd_close_instance

}

stop_service() {
	lucky_prepare
}

service_triggers() {
	procd_add_reload_trigger "$CONF"
}
