#!/bin/sh
# original version from: http://willem.engen.nl/projects/cupssmb/
# additional code by rcrsn51 2011-11-26

if [ "$1" = "" ]; then
	# list supported output types
	echo 'network smbw "Unknown" "Windows/Samba Printer"'
	exit 0
fi

job="$1"
account="$2"
title="$3"
numcopies="$4"
options="$5"
filename="$6"

if [ "$filename" = "" ]; then
	filename=-
fi

REST=$DEVICE_URI
SUBNET=${REST#*\?}
[ "$SUBNET" = "$REST" ] && SUBNET=""
REST=${REST%\?*}
PRINTER=${REST##*/}
[ "$PRINTER" = "$REST" ] && exit 1
REST=${REST%/*}
SERVER=${REST##*/}
[ "$SERVER" = "$REST" ] && exit 1
REST=${REST%/*}
WORKGROUP=${REST#*@}
if [ "$WORKGROUP" = "$REST" ]; then
  WORKGROUP=""
  PASSWORD=""
  USERNAME=""
else
  REST=${REST%@*}
  PASSWORD=${REST##*:}
  [ "$PASSWORD" = "$REST" ] && exit 1
  REST=${REST%:*}
  USERNAME=${REST##*/}
  [ "$USERNAME" = "$REST" ] && exit 1
fi

if [ -n "$SUBNET" ]; then
  SERVER=`nbtscan -q -t 5 ${SUBNET}/24 | grep -i $SERVER | cut -d " " -f 1`
  [ -z "$SERVER" ] && exit 1
fi

# and print using smbclient
echo "NOTICE: smbclient -c \"print ${filename}\" //${SERVER}/${PRINTER}" 1>&2

if [ -z "$USERNAME" ]; then
  errtxt=`smbclient -N -c "print ${filename}" //${SERVER}/${PRINTER} 2>&1`
  ret=${?}
else
  errtxt=`smbclient -U $USERNAME%$PASSWORD -W $WORKGROUP -c "print ${filename}" //${SERVER}/${PRINTER} 2>&1`
  ret=${?}
fi

#
# Handle errors
#   see backend(7) for error codes

# log message
if [ "$ret" = "0" ]; then
	echo "$errtxt" | sed 's/^/NOTICE: /' 1>&2
else
	echo "$errtxt" | sed 's/^/ERROR: /' 1>&2
fi

# "NT_STATUS_LOGON_FAILURE" -> CUPS_BACKEND_AUTH_REQUIRED
echo "$errtxt" | grep -i 'LOGON_FAILURE' >/dev/null && exit 2
# "Unable to open credentials file!" -> CUPS_BACKEND_AUTH_REQUIRED
echo "$errtxt" | grep -i 'credentials' >/dev/null && exit 2
# "NT_STATUS_BAD_NETWORK_NAME" -> CUPS_BACKEND_STOP
echo "$errtxt" | grep -i 'BAD_NETWORK_NAME' >/dev/null && exit 4

# something went wrong, don't know what -> CUPS_BACKEND_FAILED
[ "$ret" != "0" ] && exit 1

# success! -> CUPS_BACKEND_OK
exit 0
