#!/bin/bash
# -*- mode: shell-script; coding: utf-8 -*-
#
# Copyright 2002-2014 Cendio AB.
# For more information, see http://www.cendio.com

[ -h "$0" ] && ORIGIN=`ls -l "$0" | sed "s/.*-> //g"` || ORIGIN="$0"
ORIGIN=`(cd "\`dirname \"$ORIGIN\"\`"; pwd -P 2>/dev/null || pwd)`

#
# Check usage
#
if [ $# -lt 3 ]; then
    echo "Usage: $0 <printername> <description> <location> [ppd]"
    exit 1
fi

printername="$1"
description="$2"
location="$3"
ppd="$4"

[ -n "${ppd}" ] || ppd="${ORIGIN}/../share/ppd/thinlinc/nearest.ppd"

#
# Gather paths
#
if [ -z "${CUPS_PREFIX}" ]; then
    CUPS_PREFIX="/usr"
    echo "CUPS_PREFIX not defined; using ${CUPS_PREFIX}"
else
    echo "Using CUPS installed at prefix ${CUPS_PREFIX}"
fi

if [ -z "${CUPS_SERVERBIN}" ]; then
    CUPS_SERVERBIN="${CUPS_PREFIX}/lib/cups"
    echo "CUPS_SERVERBIN not defined; using ${CUPS_SERVERBIN}"
else
    echo "Using CUPS_SERVERBIN=${CUPS_SERVERBIN}"
fi

cups_backend_dir="${CUPS_SERVERBIN}/backend"
thinlinc_backend_dir="/opt/thinlinc/share/cups/backend"

#
# Verify backend dir
#
if [ ! -d "${cups_backend_dir}" ]; then
    echo "Error: The CUPS backend directory ${cups_backend_dir} does not exist."
    exit 1
fi

#
# Verify that all binaries are available
#
for command in "${CUPS_PREFIX}/sbin/lpinfo" "${CUPS_PREFIX}/sbin/lpadmin" "${CUPS_PREFIX}/sbin/cupsaccept" "${CUPS_PREFIX}/sbin/cupsenable"; do
    if [ ! -x "${command}" ]; then
        echo "Error: Cannot find required command ${command}."
        exit 1
    fi
done

#
# (Always) copy in a new version of the backend. Remove it first, in
# case it's a symlink.
#
echo "Adding CUPS backend ${printername}"
rm -f "${cups_backend_dir}/${printername}"
# Always set the same permissions as on ipp, as ipp may be installed
# root:root 700 to make it run as root. Running is also required to
# access files in /var/spool/cups on some systems.
cp -f -p "${cups_backend_dir}/ipp" "${cups_backend_dir}/${printername}"
cat "${thinlinc_backend_dir}/${printername}" > "${cups_backend_dir}/${printername}"
if [ -x /sbin/restorecon ]; then
    /sbin/restorecon "${cups_backend_dir}/${printername}"
fi

#
# Restart CUPS
#
${ORIGIN}/restart_cups
if [ $? -ne 0 ]; then
    exit 1
fi

#
# Add printer
#
"${CUPS_PREFIX}/sbin/lpadmin" -h localhost -p "${printername}" -v "${printername}:/" -D "${description}" -L "${location}" -P "${ppd}"
"${CUPS_PREFIX}/sbin/cupsenable" -h localhost "${printername}"
"${CUPS_PREFIX}/sbin/cupsaccept" -h localhost "${printername}"
