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

USE_PROCD=1

START=90
STOP=10

# default params
PROG=/usr/sbin/i2pd
USER="i2pd"
GROUP="i2pd"
PIDFILE=/var/run/i2pd.pid
DATADIR=/var/lib/i2pd
CONFFILE=/etc/i2pd/i2pd.conf

. /lib/functions.sh



i2pd_start() {
	local cfg="$1"
	local data_dir
	local addressbook_dir

	config_get data_dir "$cfg" data_dir "$DATADIR"
	config_get addressbook_dir "$cfg" addressbook_dir

	## Setting up data dir
	[ -d "$data_dir" ] || {
		mkdir -p "$data_dir"
		chown "$USER:$GROUP" "$data_dir"
		ln -s /usr/share/i2pd/certificates "$data_dir/certificates"
		[ -n "$addressbook_dir" ] && {
			[ -d "$addressbook_dir" ] || mkdir -p "$addressbook_dir"
			chown "$USER:$GROUP" "$addressbook_dir"
			ln -s "$addressbook_dir" "$data_dir/addressbook"
		}
	}

	## We need permissions
	touch "$PIDFILE"
	chown "$USER:adm" "$PIDFILE"

	procd_open_instance
	procd_set_param command "$PROG" --service --conf="$CONFFILE" --pidfile "$PIDFILE"
	## Don't know about i2pd user's HOME
	procd_set_param env "HOME=$DATADIR"
	## For debugging, provide about 512 MB on external storage for coredump and adjust /proc/sys/kernel/core_pattern
	# echo "/tmp/coredumps/core.%e.%p.%s.%t" > /proc/sys/kernel/core_pattern
	# procd_set_param limits core="unlimited unlimited"
	procd_set_param limits nofile=4096
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_set_param user "$USER"
	procd_set_param pidfile "$PIDFILE"
	procd_close_instance
}


start_service() {
	local instance="$1"
	local instance_found=0

	config_cb() {
		local type="$1"
		local name="$2"
		[ "$type" = "i2pd" ] && [ -n "$instance" ] && [ "$instance" = "$name" ] && instance_found=1
	}

	config_load i2pd

	if [ -n "$instance" ]; then
		[ "$instance_found" -gt 0 ] || return
		i2pd_start "$instance"
	else
		config_foreach i2pd_start i2pd
	fi
}
