#!/bin/bash
# 
# Glpr: print via lpr .
#
# *      Copyright 2010 Francesco Cappelli
# *      
# *      This program is free software; you can redistribute it and/or modify
# *      it under the terms of the GNU General Public License as published by
# *      the Free Software Foundation; either version 2 of the License, or
# *      (at your option) any later version.
# *      
# *      This program is distributed in the hope that it will be useful,
# *      but WITHOUT ANY WARRANTY; without even the implied warranty of
# *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# *      GNU General Public License for more details.
# *      
# *      You should have received a copy of the GNU General Public License
# *      along with this program; if not, write to the Free Software
# *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# *      MA 02110-1301, USA.
# *
#
#
ZENITY=`which zenity`
GXMESSAGE=`which gxmessage`
#
# Localization
#
if [ "${LANG:0:2}" == "it" ] ; then
#
info="Glpr: semplice interfaccia grafica per lpr (presente 
nel pacchetto cups-bsd) implementata tramite bash, zenity 
e gxmessage.

lpr consente di stampare aggirando 
il bug (Debian Bug report logs - #583738) presente 
nella versione 8.71~dfsg2-6 del pacchetto ghostscript 
installata su Debian Squeeze.

I formati che lpr è in grado di interpretare sono: 
.pdf .gif .png .jpg .JPG .jpeg 
.tiff .ps .txt .pbm .pnm .ppm 
oltre che i file di testo senza estensione.
I percorsi di file che contengono punti diversi dal separatore 
di estensione (come i file nascosti o i file contenuti in 
cartelle nascoste) non sono riconosciuti.

ATTENZIONE!!! Anche se lpr esce con uno status positivo non è 
detto che la stampa sia avvenuta correttamente: è sempre 
necessario controllare; è possibile verificare se le 
istruzioni siano state inviate correttamente al server di 
stampa visitando l'indirizzo http://localhost:631/jobs/ 
(se non è presente alcuna voce la trasmissione è avvenuta 
correttamente). 

Selezionare per tutti i parametri un valore valido: in caso 
contrario il programma cercherà di individuare la voce erronea 
e di sostituirla con il valore di default; nel caso in cui la 
voce sfuggisse ai controlli lpr genererà un messaggio d'errore.

Per poter specificare i parametri di stampa il file lpr-par 
deve avere il permesso di lettura, deve essere collocato nelle 
aposite cartelle ( /home/utente/.glpr/ oppure /etc/glpr/ ) 
e deve essere nel formato corretto: 
è necessario specificare almeno una stampante disponibile 
(fino a 3), almeno una qualità di stampa connessa con una 
risoluzione supportata (fino a 6), nonchè almeno un modello di 
colore (fino a 3); è necessario specificare il primo valore, 
lasciare eventualmente vuoti gli altri campi; 
è inoltre possibile specificare una cartella all'interno della 
home utende da dove far partire la ricerca del file. 
Per conoscere i valori possibili per i parametri lanciare da 
terminale il seguente comando: 
lpoptions -p <nomePrintnte> -l | grep <parametro> 

Il file deve essere nella forma seguente: 

# --------------------------------------- 
#
# printer1=nomeStampante1
#
printer1=nomeStampante1
printer2=nomeStampante2
printer3=nomeStampante3
#
#
# qual1=qualità1
#
qual1=qualità1
qual2=qualità2
qual3=qualità3
qual4=qualità4
qual5=qualità5
qual6=qualità6
#
#
# Resolution1=risoluzione1
#
Resolution1=risoluzione1
Resolution2=risoluzione2
Resolution3=risoluzione3
Resolution4=risoluzione4
Resolution5=risoluzione5
Resolution6=risoluzione6
#
# (resolution1=720x360dpi per esempio)
#
#
# ColorModel1=modelloColore1
#
ColorModel1=modelloColore1
ColorModel2=modelloColore2
ColorModel3=modelloColore3
#
#
# direct=cartellaFile
#
direct=cartellaFile
#
# ---------------------------------------
"
#
intro="Questa procedura consente di stampare un 
documento tramite lpr. 
Sarà ora richiesto quale file si desidera stampare."
#
sel1="Parametri di stampa:
 " 
#
sel2=" 
Utilizzare i pulsanti sottostanti per modificarli. 

Premere su \"Other\" per scegliere il numero di copie, 
l'intervallo di pagine e se stampare 
solo le pagine pari o quelle dispari."
#
oth1="Altri parametri di stampa:
 "
#
oth2=" 
Utilizzare i pulsanti sottostanti per modificarli."
#
warnext="I formati validi sono: 
.pdf .gif .png .jpg .JPG .jpeg 
.tiff .ps .txt .pbm .pnm .ppm 
oltre che i file di testo senza estensione. 

I percorsi di file che contengono punti 
diversi dal separatore di estensione 
(come i file nascosti o i file contenuti 
in cartelle nascoste) non sono riconosciuti. 

Convertire il file e seleziona la nuova versione."
#
pridir1="Scegliere \"Print\" per stampare il file"
#
pridir2="usando i parametri di default.
(essi possono essere modificati all'indirizzo 
 http://localhost:631/printers/ )

Scegliere \"Cancel\" per annullare la stampa. 

Scegliere \"Help\" per sapere come impostare 
i parametri di stampa (la procedura 
sarà annullata)."
#
else # English
#
info="Glpr: simple graphical interface for lpr (in cups-bsd package)
using bash, zenity and gxmessage.

lpr allows to print despite the serius 
bug (Debian Bug report logs - #583738) present
in the 8.71~dfsg2-6 version of the ghostscript
package installed on Debian Squeeze.

Valid formats are the follows: 
.pdf .gif .png .jpg .JPG .jpeg 
.tiff .ps .txt .pbm .pnm .ppm 
and text files without extension. 
File paths with points other then extension separator 
(like hidden files, or files in hidden folders) are not valid. 

CAUTION!!! Even if lpr exits correctly there may be printing 
problems: it's possible to check this visiting the URL 
http://localhost:631/jobs/ (if no item is present cups have 
encountered no problems).

Select for all parameters valid values, otherwise the script
will try to identify the wrong item and  to replace it with 
the standard value; in case of failure of the check lpr will 
report an error message.

To specify printing parameters the file lpr-par has to be 
readable and has to be placed in the right folder
( /home/utente/.glpr/ or /etc/glpr/ ) and has to be in 
the right format:
it is necessary to specify at least the name of an aviable 
printer (up to 3), at least a print quality related to a 
supported resolution (up to 6), at least a color model 
(up to 3); it is necessary to specify the first item, 
leave others eventually blank;
it is possible to specify a folder in user's home 
directory too from wich to start file search.
To learn possible parameters value run in a shell
lpoptions -p <PrinterName> -l | grep <parameter>

lpr-par has to be in the following format:

# --------------------------------------- 
#
# printer1=printerName1 
#
printer1=printerName1 
printer2=printerName2 
printer3=printerName3 
#
#
# qual1=quality1
#
qual1=quality1
qual2=quality2
qual3=quality3 
qual4=quality4
qual5=quality5
qual6=quality6 
#
#
# Resolution1=resolution1
#
Resolution1=resolution1 
Resolution2=resolution2 
Resolution3=resolution3
Resolution4=resolution4 
Resolution5=resolution5
Resolution6=resolution6 
#
# (resolution1=720x360dpi for example)
#
#
# ColorModel1=colormodel1
#
ColorModel1=colormodel1
ColorModel2=colormodel2
ColorModel3=colormodel3
#
#
# direct=directoryName
#
direct=directoryName
#
# ---------------------------------------
"
#
intro="You can print a document via lpr. 
Press \"OK\" and select the file."
#
sel1="Print parameters:
 "
#
sel2="  
Use the buttons to modify them. 

Choose \"Other\" to modify the number of copies,
the interval of pages to print and if to print 
only even or odd pages."
#
oth1="Other print parameters:
 "
#
oth2="  
Use the buttons to modify them."
#
warnext="Valid formats are the follows: 
.pdf .gif .png .jpg .JPG .jpeg 
.tiff .ps .txt .pbm .pnm .ppm 
and text files without extension. 

File paths with points other then extension 
separator (like hidden files, or files in 
hidden folders) are not valid. 

Convert the file and select the new version."
#
pridir1="Choose \"Print\" to print the file"
#
pridir2="using default parameters.
(they can be set visiting the URL 
 http://localhost:631/printers/ )

Choose \"Cancel\" to abort. 

Choose \"Help\" to know how to set printing parameters 
(printing procedure will be aborted)."
#
fi
#
###############
#
# It reads the file glpr-par if possible
#
if [ -r /home/$USER/.glpr/glpr-par ] ; then
. /home/$USER/.glpr/glpr-par
elif [ ! -r /home/$USER/.glpr/glpr-par ] && [ -r /etc/glpr/glpr-par ] ; then
. /etc/glpr/glpr-par
fi
#
#
$ZENITY --info --title "Print via lpr" --text "$intro"
#
if [ -d /home/$USER/$direct ] ; then
cd /home/$USER/$direct
fi
#
EXT="1"
until [ "$EXT" == "0" ] ;
do
file=`$ZENITY --title "File" --file-selection`
#
# It checks if file type is accepted by lpr
numpoint="${file//[^.]/}"	# gives the number of points found in file path
ext="???"
if [ "$numpoint" == "." ] ; then
ext="${file#*.}"
fi
if [ -n "$file" ] && ( [ "$numpoint" == "" ] || [ "$ext" == "pdf" ] || [ "$ext" == "gif" ] || [ "$ext" == "png" ] || [ "$ext" == "jpg" ] || [ "$ext" == "jpeg" ] || [ "$ext" == "JPG" ] || [ "$ext" == "tiff" ] || [ "$ext" == "ps" ] || [ "$ext" == "txt" ] || [ "$ext" == "pbm" ] || [ "$ext" == "pnm" ] || [ "$ext" == "ppm" ] ) ; then
EXT="0"
elif [ -z "$file" ] ; then
break
else
EXT="1"
$ZENITY --warning --text "The file format \".$ext\" is not supported by lpr. 

$warnext"
fi
done
#
#
if [ "$EXT" == "0" ] ; then
#
# Variables
printer="$printer1"
resol="$Resolution1"
qual="$qual1"
qualResol="$qual|$resol"
colmod="$ColorModel1"
numcopy="1"
interv="all"
oddeven="all"
#
if ( [ -r /home/$USER/.glpr/glpr-par ] || [ -r /etc/glpr/glpr-par ] ) && [ -n "$printer" ] && [ -n "$qual" ] && [ -n "$resol" ] && [ -n "$colmod" ] ; then
#
FX="0"
#
GXMSG="0"
until [ "$GXMSG" == "_Print" ] ;
do
GXMSG=`$GXMESSAGE -print -center -name "Print" -title "Print" -buttons "Prin_ter:11,_Quality:12,Co_lor:13,Othe_r:14,_Print:15,_Cancel:16,_Help:17" -default "_Print" "$sel1
File Name:	\"$file\" 
 
Printer Name:	\"$printer\"
Quality:		\"$qual\"
Color Model:	\"$colmod\"
$sel2"`
if [ "$GXMSG" == "Prin_ter" ] ; then
printer=`$ZENITY --title "Printer" --text "Choose the name of the printer." --list --radiolist --column "" --column "printer" TRUE "$printer1" FALSE "$printer2" FALSE "$printer3" --height=220`
if [ -z "$printer" ] ; then
printer="$printer1"
fi
elif [ "$GXMSG" == "_Quality" ] ; then
qualResol=`$ZENITY --title "Quality" --text "Choose the quality." --list --radiolist --print-column="2,3" --separator="|" --column "" --column "quality" --column "resolution" TRUE "$qual1" "$Resolution1" FALSE "$qual2" "$Resolution2" FALSE "$qual3" "$Resolution3" FALSE "$qual4" "$Resolution4" FALSE "$qual5" "$Resolution5" FALSE "$qual6" "$Resolution6" --height=300 --width=350`
qual=${qualResol%|*}
resol=${qualResol#*|}
if [ -z "$resol" ] ; then
resol="$Resolution1"
qual="$qual1"
fi
elif [ "$GXMSG" == "Co_lor" ] ; then
colmod=`$ZENITY --title "Color" --text "Choose the color model." --list --radiolist --column "" --column "color" TRUE "$ColorModel1" FALSE "$ColorModel2" FALSE "$ColorModel3" --height=230`
if [ -z "$colmod" ] ; then
colmod="$ColorModel1"
fi
elif [ "$GXMSG" == "Othe_r" ] ; then
#
GXMSG2="0"
until [ "$GXMSG2" == "_OK" ] ;
do
GXMSG2=`$GXMESSAGE -print -center -name "Other" -title "Other" -buttons "_Copies:21,_Interval:22,O_dd/Even:23,_OK:24,_Cancel:25" -default "_OK" "$oth1
Number of copies:	\"$numcopy\"
Interval:			\"$interv\"
Odd/Even pages:	\"$oddeven\"
$oth2 "`
if [ "$GXMSG2" == "_Copies" ] ; then
numcopy=`$ZENITY --title "Copies" --text "Set the number of copies." --entry --entry-text="1"`
(( "$numcopy" >= "1" )) 2> /dev/null
exnum="$?"
if [ "$exnum" == "1" ] || [ -z "$numcopy" ] ; then
numcopy="1"
fi
elif [ "$GXMSG2" == "_Interval" ] ; then
interv=`$ZENITY --title "Interval" --text "Set the interval of pages to print 
in the form 1-3,5,7,10-12 . 
\"-\" identify an interval, 
\",\" separate intervals or single pages. 
Write \"all\" to print all pages." --entry --entry-text="all"`
if [ -z "$interv" ] ; then
interv="all"
fi
elif [ "$GXMSG2" == "O_dd/Even" ] ; then
oddeven=`$ZENITY --title "Odd/Even" --text "Choose if to print all pages, 
only odd or only even pages." --list --radiolist --column "" --column "odd/even" TRUE "all" FALSE "odd" FALSE "even" --height=250`
if [ -z "$oddeven" ] ; then
oddeven="all"
fi
elif [ "$GXMSG2" == "_OK" ] ; then
GXMSG2="_OK"
else
GXMSG2="1"
# reset values
numcopy="1"
interv="all"
oddeven="all"
break
fi
done
#
elif [ "$GXMSG" == "_Help" ] ; then
$GXMESSAGE -center -name "Glpr" -title "Informations on Glpr" "$info"
elif [ "$GXMSG" == "_Print" ] ; then
GXMSG="_Print"
else
GXMSG="1"
break
fi
done
if [ "$GXMSG" == "_Print" ] ; then
CONF="0"
else CONF="1"
fi
#
# If the file glpr-par is not found or it is not in the correct format it asks if to print using default parameters
else
FX="1"
GXMSG=`$GXMESSAGE -print -center -name "Print" -title "Print" -buttons "_Print:12,_Cancel:13,_Help:14" -default "_Print" "$pridir1
\"$file\" 
$pridir2"`
if [ "$GXMSG" == "_Print" ] ; then
CONF="0"
elif [ "$GXMSG" == "_Cancel" ] ; then
CONF="1"
elif [ "$GXMSG" == "_Help" ] ; then
$GXMESSAGE -center -name "Glpr" -title "Informations on Glpr" "$info"
else
GXMSG="1"
break
fi
fi
fi
#
if [ "$interv" == "all" ] ; then
interv="1-1000000"
fi
#
# It execute lpr to print
#
if [ "$FX" == "1" ] && [ "$CONF" == "0" ] ; then
error=$(lpr -p -o cpi=9 -o lpi=5 "$file" 2>&1 >/dev/null)
fi
#
if [ "$FX" == "0" ] && [ "$CONF" == "0" ] ; then
error=$(lpr -P "$printer" -p -o cpi=9 -o lpi=5 -# "$numcopy" -o Resolution="$resol" -o ColorModel="$colmod" -o page-ranges="$interv" -o page-set="$oddeven" "$file" 2>&1 >/dev/null)
fi
#
#
# lpr error message
#
if [ -n "$error" ] ; then
$ZENITY --error --text "lpr error message: 

 $error 

Print aborted."
fi
#
#
# Esce
exit 0
#
#
