#!/usr/bin/python
# -*- coding: UTF-8 -*-

# Copyright 2006-2007 (C) Raster Software Vigo (Sergio Costas)
#
# This file is part of GtkPSproc
#
# GtkPSproc 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 3 of the License, or
# (at your option) any later version.
#
# GtkPSproc 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, see <http://www.gnu.org/licenses/>.

import sys
import tempfile
import subprocess
import pwd
import os

def send_error(message):

	try:
		fichero=open("/var/tmp/gtkpsproc/error.log","a")
	except:
		return
		
	fichero.write("backend "+str(pwd.getpwuid(os.getuid())[0])+": "+message+"\n")
	fichero.close()


send_error("abierto")

if len(sys.argv)==1:
	send_error("capacidades");
	print 'direct psproc:/ "GtkPSproc" "GtkPSproc backend"'
	sys.exit(0)
elif len(sys.argv)==6: # use stdin
	send_error("stdin")
	printfile=sys.stdin
elif len(sys.argv)==7: # use file
	send_error("fichero")
	printfile=open(sys.argv[6],"r")
else:
	send_error("param incorr")
	tempo=open("/var/tmp/psproc.log","w")
	tempo.write("Se han pedido parametros incorrectos\n")
	for elem in sys.argv:
		tempo.write(elem+"\n")
	tempo.close()
	sys.exit(0)

username=sys.argv[2]
title=sys.argv[3]
copies=sys.argv[4]

directory="/var/tmp/gtkpsproc/"+username+"/"

outfilename=tempfile.mktemp(dir="",prefix="gtkpsproc_",suffix=".ps")

# copy the PS to the temporary directory
try:
	outfile=open(directory+"/"+outfilename,"w")
except :
	print "ERROR: Can't write to GtkPSproc queue. Be sure that you have the applet running."
	sys.exit(0)

for elem in printfile:
	outfile.write(elem)
outfile.close()

# create the data file with the directory

outfile2name=tempfile.mktemp(dir=directory,prefix="gtkpsproc_",suffix=".txt")
try:
	outfile2=open(outfile2name,"w")
except :
	print "ERROR: Can't write to GtkPSproc queue. Be sure that you have the applet running."
	sys.exit(0)

outfile2.write(str(outfilename)+"\n"+str(title)+"\n"+str(copies))
outfile2.close()

h=subprocess.Popen("chmod 666 "+directory+"/"+outfilename,shell=True,bufsize=32768)
h.wait()
h=subprocess.Popen("chmod 666 "+outfile2name,shell=True,bufsize=32768)
h.wait()
h=subprocess.Popen("mv "+outfile2name+" "+directory+"list/",shell=True,bufsize=32768)
h.wait()

sys.exit(0)
