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

USE_PROCD=1
START=80

start_instance() {
	local section="$1"

	config_get_bool enabled "$section" enabled 1
	[ "$enabled" != "1" ] && return 0

	config_get atsign "$section" atsign
	if [ -z "$atsign" ]; then
		echo "sshnpd: atsign for this device is mandatory"
		return 1
	fi

	config_get manager "$section" manager
	if [ -z "$manager" ]; then
		echo "sshnpd: manager for this device is mandatory"
		return 1
	fi

	config_get device "$section" device
	if [ -z "$device" ]; then
		echo "sshnpd: device name is mandatory"
		return 1
	fi

	config_get user "$section" user
	if [ -z "$user" ]; then
		user='root'
	fi

	config_get home "$section" home
	if [ -z "$home" ]; then
        if [ "$user" = "root" ]; then
				home='/root'
        else
				home="/home/${user}"
        fi
	fi

	if [ ! -f "${home}/.atsign/keys/${atsign}_key.atKeys" ]; then
		echo "sshnpd: WARNING atsign keys not found in default location"
	fi

	if [ ! -d "${home}/.ssh" ]; then
		mkdir ${home}/.ssh
		chmod 700 ${home}/.ssh
	fi

	if [ ! -f "${home}/.ssh/authorized_keys" ]; then
		touch ${home}/.ssh/authorized_keys
		chmod 600 ${home}/.ssh/authorized_keys
	fi

	config_get args "$section" args

	config_get pidfile "$section" pidfile

	procd_open_instance "$section"
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_set_param env USER=${user} HOME=${home}
	procd_set_param command /usr/bin/sshnpd -a ${atsign} -m ${manager} -d ${device} ${args}
	procd_set_param respawn ${respawn_threshold:-3600} ${respawn_timeout:-5} ${respawn_retry:-5}
	[ -n "$pidfile" ] && procd_set_param pidfile "$pidfile"

	[ -n "$pidfile" ] && procd_append_param env "SSHNPD_PIDFILE=$pidfile"

	procd_close_instance
}

start_service() {
	local instance=$1

	config_load 'sshnpd'

	if [ -n "$instance" ]; then
		start_instance "$1"
	else
		config_foreach start_instance 'sshnpd'
	fi
}
