#!/bin/sh /etc/rc.common
# Copyright (C) 2006-2011 OpenWrt.org

START=50
STOP=50

USE_PROCD=1

TORRC_GEN="/tmp/torrc"

handle_conf_file() {
	local conf_path="$1"
	if [ -f "$conf_path" ] || [ -d "$conf_path" ]; then
		echo "%include $conf_path"
	fi
}

generate_conf() {
	local default_conf generated_conf

	config_load tor
	config_get default_conf conf default "/etc/tor/torrc"
	config_get generated_conf conf generated "/tmp/torrc"
	TORRC_GEN="$generated_conf"

	{
	echo "## This file was automatically generated please do not edit here !"
	config_list_foreach "conf" head_include handle_conf_file
	echo "%include $default_conf"
	config_list_foreach "conf" tail_include handle_conf_file
	} > "$TORRC_GEN"
}

reload_service() {
	procd_send_signal tor
}

start_service() {
	mkdir -m 0700 -p /var/lib/tor
	chown -R tor:tor /var/lib/tor

	mkdir -m 0755 -p /var/log/tor
	chown -R tor:tor /var/log/tor

	generate_conf

	procd_open_instance
	procd_set_param command /usr/sbin/tor --runasdaemon 0
	procd_append_param command -f "$TORRC_GEN"
	procd_set_param respawn
	procd_close_instance
}
