#!/sbin/openrc-run
# Copyright 2009-2011 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2

INSTANCE="${SVCNAME#*.}"
if [ -z "${INSTANCE}" -o "${SVCNAME}" = "ekey-ulusbd" ]; then
	INSTANCE="ekey-ulusbd"
fi

: ${SOCKET_PATH:=/var/run/ekey-ulusbd-${EKEY_SERIAL}}

description="EntropyKey Userland USB Daemon"

pidfile=/var/run/$SVCNAME.pid
command=/usr/libexec/ekey-ulusbd
command_args="-P ${pidfile} -p ${SOCKET_PATH}"

depend() {
	 need localmount
}

start() {
	if [ -z ${USB_BUS} ]; then
		set -- $(lsusb -v -d 20df:0001 | \
			egrep '(^Bus|iSerial)' | \
			grep -B1 "${EKEY_SERIAL}" | \
			head -n 1 | \
			cut -c 5-7,15-18)
		USB_BUS=$1
		USB_DEV=$2
	fi

	ebegin "Starting ${description}"
	start-stop-daemon \
		--start --pidfile ${pidfile} \
		--exec ${command} -- \
		${command_args} \
		-b $(printf %03d ${USB_BUS}) -d $(printf %03d ${USB_DEV}) -D
	eend $?
}
