#!/bin/sh

LOG=/var/log/cups/cups-capture.log
(   
    date >>$LOG
    echo -n "$0 "
    printf '"%s" ' "$@" 
    echo 
) >>$LOG

DIR=/usr

export CONFIG="$DIR/local/etc/cups-capture.yml"

# Run the command
function doit () {
    if [ $# -eq 6 ]; then
        unset TMPDIR
        FILE="$(mktemp -tp "/tmp" cups-dw-$1-XXXXXXXXXX)"
        echo INFO: FILE=$FILE 6=$6
        cat $6 >$FILE
        arg=( "$@" )
        arg[5]=$FILE
        chmod o+r "$FILE"
        $DIR/bin/cups-capture "${arg[@]}" || exit 17
        rm -f $FILE
    else
        $DIR/bin/cups-capture "$@" || exit 18
    fi
}

# Tag untagged lines as ERROR:
function tag_error () { 
    sed -E '/^\w+:/!s/^/ERROR: /' 
}

# Tag untagged lines as INFO:
function tag_info () { 
    sed -E '/^\w+:/!s/^/INFO: /' 
}

# These next 2 lines will log stderr and stdout to $LOG 
# but also send them to stderr and stdout untouched
exec 3>&1
{ doit "$@" | tag_info | tee -a $LOG; } 2>&1 1>&3 | tag_error | tee -a $LOG 1>&2
