#!/sbin/openrc-run

start() {

	if [ -z "${can_speed}" -o -z "${tty_baud}" -o -z "${tty_device}" -o -z "${can_device}" ]; then
		eerror "CAN speed, CAN device, tty_baud or tty_device not set"
		return 1
	fi

	if ! grep -q slcan /proc/modules; then
		einfo "Loading module slcan"
		modprobe slcan || return 1
	fi

	ebegin "Creating can0 at speed ${can_speed} on device ${tty_device}"		
	einfo "Setting baudrate of ${tty_device} to ${tty_baud}"
	stty -F /dev/${tty_device} ${tty_baud} line 0 cs8 -onlcr -echo raw min 100 time 2
	sleep 1
	einfo "Set bitrate of slcan on ${tty_device} to ${can_speed}: "
	echo -e -n "C\rF\r${can_speed}\rO\r" > /dev/${tty_device}
	sleep 1
	einfo "Starting slcand"
	start-stop-daemon --start --background --make-pidfile \
					  --pidfile /var/run/slcand.pid \
					  --exec /usr/bin/slcand -- ${tty_device} ${can_device}
	sleep 1
	ifconfig ${can_device} up
	eend $?
}

stop() {
	ebegin "Stopping slcand"
	start-stop-daemon --stop --quiet --pidfile /var/run/slcand.pid
	sleep 1
	rmmod slcan
	eend $?
}
