#!/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



start_service() {
	local data_dir
	local addressbook_dir

	config_load i2pd

	config_get data_dir i2pd data_dir
	config_get addressbook_dir i2pd addressbook_dir

	## Setting up data dir
	if [ ! -d "$data_dir" ]; then
		mkdir -p "$data_dir"
		ln -s /usr/share/i2pd/certificates "$data_dir/certificates"
		ln -s /etc/i2pd/tunnels.conf "$data_dir/tunnels.conf"
		if [ -n "$addressbook_dir" ]; then
			if [ ! -d "$addressbook_dir" ]; then
				mkdir -p "$addressbook_dir"
			fi
			ln -s "$addressbook_dir" "$data_dir/addressbook"
		fi
	fi

	## We need permissions
	chown "$USER:$GROUP" "$data_dir"
	chown "$USER:$GROUP" "$addressbook_dir"
	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"
	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
}
