#!/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)`

# Gather paths
#
if [ -z "${CUPS_PREFIX}" ]; then
    CUPS_PREFIX="/usr"
    echo "CUPS_PREFIX not defined; using ${CUPS_PREFIX}"
fi

#
# Restart CUPS
#
echo "Restarting CUPS to make it aware of changes..."
errors=`mktemp`
for name in cups cupsd cupsys; do
        /bin/systemctl restart "${name}" >>${errors} 2>&1 && break
done
if [ $? -ne 0 ]; then
    echo "Error restarting cups/cupsd/cupsys:" >&2
    cat "${errors}" >&2
    rm "${errors}"
    exit 1
fi
rm "${errors}"
echo "Waiting for CUPS to start..."
for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30; do
    OUTPUT=$("${CUPS_PREFIX}/sbin/lpinfo" -h localhost -v 2>/dev/null)
    if [ $? -eq 0 ]; then
        if echo "${OUTPUT}" | grep "${printername}" >/dev/null; then
            break
        else
            echo "CUPS started but without ${printername}"
            exit 1
        fi
    fi
    sleep 1
done
if [ "$i" -eq 30 ]; then
    echo "Timeout waiting for CUPS to start"
    exit 1
fi

