#!/bin/sh
# Copyright (C) 2005-2014 NowRush Studio
# Author: hackpascal <hackpascal@gmail.com>

. $IPKG_INSTROOT/lib/functions.sh

PRODUCT=$1
ACTION=$2

DEVICES=

check_printer() {
	local cfg=$1
	local enabled
	local device_id
	local bind_ip
	local port
	local bidirect
	local device_file
	local args=""
	local pid_file

	config_get_bool enabled "$cfg" enabled 0
	[ "$enabled" -eq 0 ] && return 0

	config_get device_id "$cfg" device ""
	config_get bind_ip "$cfg" bind "0.0.0.0"
	config_get port "$cfg" port ""
	config_get_bool bidirect "$cfg" bidirectional "0"

	if [ -z "$device_id" ] || [ -z "$port" ]; then
		return
	fi

	if [ x"$PRODUCT" != x"$device_id" ]; then
		return
	fi

	device_file=`echo "$DEVICES" | grep $device_id | cut -d , -f 1`

	if [ "$ACTION" = "add" ] && [ -z "$device_file" ]; then
		return
	fi

	pid_file=/var/run/p910${port}d.pid
	[ -f $pid_file ] && kill `cat $pid_file` 2>/dev/null

	if [ "$ACTION" = "add" ]; then
		if [ "$bidirect" != 0 ]; then
			args='-b'
		fi

		logger "usb_printer: start p910nd on $bind_ip:$port for /dev/usb/$device_file"
		/usr/sbin/p910nd $args -f /dev/usb/$device_file -i $bind_ip $port
	fi
}

if [ -z "$PRODUCT" ] || [ -z "$ACTION" ]; then
	echo "Arguements required"
	exit 1
fi

if [ "$ACTION" != "add" ] && [ "$ACTION" != "remove" ]; then
	echo "Invalid action arguement"
	exit 1
fi

DEVICES=`/usr/bin/detectlp`

config_load usb_printer

config_foreach check_printer printer
