#!/bin/bash
# -*- mode: shell-script; coding: utf-8 -*-
#
# Copyright 2008-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)`

#
# 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_config_dir="/etc/cups"
cups_filter_dir="${CUPS_SERVERBIN}/filter"
thinlinc_filter_dir="/opt/thinlinc/share/cups/filter"

for filter in thinlinc-ps2pdf; do
    #
    # (Always) copy in a new version of the filter. Remove it first,
    # in case it's a symlink.
    #
    echo "Adding CUPS filter ${filter}"
    rm -f "${cups_filter_dir}/${filter}"
    # Always set the same permissions as on pstops, as pstops 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_filter_dir}/pstops" "${cups_filter_dir}/${filter}"
    cat "${thinlinc_filter_dir}/${filter}" > "${cups_filter_dir}/${filter}"
    if [ -x /sbin/restorecon ]; then
        /sbin/restorecon "${cups_filter_dir}/${filter}"
    fi
    # Also add a configuration file telling cups what the filter does
    rm -f "${cups_config_dir}/${filter}.convs"
    cat "${thinlinc_filter_dir}/${filter}.convs" > "${cups_config_dir}/${filter}.convs"
    if [ -x /sbin/restorecon ]; then
        /sbin/restorecon "${cups_config_dir}/${filter}.convs"
    fi
done

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

