#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# PyKota : Print Quotas for CUPS
#
# (c) 2003-2009 Jerome Alet <alet@librelogiciel.com>
# 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 3 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, see <http://www.gnu.org/licenses/>.
#
# $Id$
#
#

import sys
import socket
import errno
import signal
import xmlrpclib

try :
    import PAM
except ImportError :
    hasPAM = False
else :
    hasPAM = True

import pykota.appinit
from pykota.utils import run
from pykota.commandline import PyKotaOptionParser, \
                               checkandset_positiveint
from pykota.errors import PyKotaToolError, \
                          PyKotaCommandLineError, \
                          PyKotaTimeoutError
from pykota.tool import Tool

class PyKotaNotify(Tool) :
    """A class for pknotify."""
    def UTF8ToUserCharset(self, text) :
        """Converts from UTF-8 to user's charset."""
        if text is None :
            return None
        else :
            return text.decode("UTF-8", "replace").encode(self.charset, "replace")

    def userCharsetToUTF8(self, text) :
        """Converts from user's charset to UTF-8."""
        if text is None :
            return None
        else :
            return text.decode(self.charset, "replace").encode("UTF-8", "replace")

    def sanitizeMessage(self, msg) :
        """Replaces \\n and returns a messagee in xmlrpclib Binary format."""
        return xmlrpclib.Binary(self.userCharsetToUTF8(msg.replace("\\n", "\n")))

    def convPAM(self, auth, queries=[], userdata=None) :
        """Prepares PAM datas."""
        response = []
        for (query, qtype) in queries :
            if qtype == PAM.PAM_PROMPT_ECHO_OFF :
                response.append((self.password, 0))
            elif qtype in (PAM.PAM_PROMPT_ECHO_ON, PAM.PAM_ERROR_MSG, PAM.PAM_TEXT_INFO) :
                self.printInfo("Unexpected PAM query : %s (%s)" % (query, qtype), "warn")
                response.append(('', 0))
            else:
                return None
        return response

    def checkAuth(self, username, password) :
        """Checks if we could authenticate an username with a password."""
        if not hasPAM :
            raise PyKotaToolError, "You MUST install PyPAM for this functionnality to work !"
        else :
            retcode = False
            self.password = password
            auth = PAM.pam()
            auth.start("passwd")
            auth.set_item(PAM.PAM_USER, username)
            auth.set_item(PAM.PAM_CONV, self.convPAM)
            try :
                auth.authenticate()
                auth.acct_mgmt()
            except PAM.error, response :
                self.printInfo(_("Authentication error for user %(username)s : %(response)s") % locals(), "warn")
            except :
                self.printInfo(_("Internal error : can't authenticate user %(username)s") % locals(), "error")
            else :
                self.logdebug("Entered password is correct for user %s" % username)
                retcode = True
            return retcode

    def alarmHandler(self, signum, frame) :
        """Alarm handler."""
        raise PyKotaTimeoutError, _("The end user at %s:%i didn't answer within %i seconds. The print job will be cancelled.") % (self.destination, self.port, self.timeout)

    def main(self, arguments, options) :
        """Notifies or asks questions to end users through PyKotIcon."""
        try :
            (self.destination, self.port) = options.destination.split(":")
            self.port = int(self.port)
        except ValueError :
            self.destination = options.destination
            self.port = 7654

        try :
            self.timeout = options.timeout
            if self.timeout < 0 :
                raise ValueError
        except (ValueError, TypeError) :
            self.timeout = 0

        if self.timeout :
            signal.signal(signal.SIGALRM, self.alarmHandler)
            signal.alarm(self.timeout)

        try :
            try :
                server = xmlrpclib.ServerProxy("http://%s:%s" % (self.destination, self.port))
                if options.action == "ask" :
                    try :
                        if options.denyafter < 1 :
                            raise ValueError
                    except (ValueError, TypeError) :
                        options.denyafter = 1
                    labels = []
                    varnames = []
                    varvalues = {}
                    for arg in arguments :
                        try :
                            (label, varname, varvalue) = arg.split(":", 2)
                        except ValueError :
                            raise PyKotaCommandLineError, "argument '%s' is invalid !" % arg
                        labels.append(self.sanitizeMessage(label))
                        varname = varname.lower()
                        varnames.append(varname)
                        varvalues[varname] = self.sanitizeMessage(varvalue)

                    passnumber = 1
                    authok = None
                    while (authok != "AUTH=YES") and (passnumber <= options.denyafter) :
                        result = server.askDatas(labels, varnames, varvalues)
                        if not options.checkauth :
                            break
                        if result["isValid"] :
                            if ("username" in varnames) and ("password" in varnames) :
                                if self.checkAuth(self.UTF8ToUserCharset(result["username"].data[:]),
                                                  self.UTF8ToUserCharset(result["password"].data[:])) :
                                    authok = "AUTH=YES"
                                else :
                                    authok = "AUTH=NO"
                            else :
                                authok = "AUTH=IMPOSSIBLE"
                        passnumber += 1

                    if options.checkauth and options.denyafter \
                       and (passnumber > options.denyafter) \
                       and (authok != "AUTH=YES") :
                        print "DENY"
                    if result["isValid"] :
                        for varname in varnames :
                            if (varname != "password") \
                               and ((varname != "username") or (authok in (None, "AUTH=YES"))) :
                                print "%s=%s" % (varname.upper(), self.UTF8ToUserCharset(result[varname].data[:]))
                        if authok is not None :
                            print authok
                elif options.action == "confirm" :
                    print server.showDialog(self.sanitizeMessage(arguments[0]), True)
                elif options.action == "notify" :
                    print server.showDialog(self.sanitizeMessage(arguments[0]), False)

                if options.quit :
                    server.quitApplication()
            except (xmlrpclib.ProtocolError, socket.error, socket.gaierror), msg :
                print options.noremote
                #try :
                #    errnum = msg.args[0]
                #except (AttributeError, IndexError) :
                #    pass
                #else :
                #    if errnum == errno.ECONNREFUSED :
                #        raise PyKotaToolError, "%s : %s" % (str(msg), (_("Are you sure that PyKotIcon is running and accepting incoming connections on %s:%s ?") % (self.destination, self.port)))
                self.printInfo("%s : %s" % (_("Connection error"), str(msg)), "warn")
            except PyKotaTimeoutError, msg :
                self.printInfo(msg, "warn")
                print "CANCEL"      # Timeout occured : job is cancelled.
        finally :
            if self.timeout :
                signal.alarm(0)

if __name__ == "__main__" :
    sys.stderr.write("The pknotify command line tool is currently broken in this development tree. Please use a stable release instead.\n")
    sys.exit(-1)
    parser = PyKotaOptionParser(description=_("Notifies end users who have launched the PyKotIcon client side graphical desktop helper."),
                                usage="pknotify [options] [arguments]")
    parser.add_option("-a", "--ask",
                            action="store_const",
                            const="ask",
                            dest="action",
                            help=_("Ask something to the remote user, then print the result."))
    parser.add_option("-c", "--confirm",
                            action="store_const",
                            const="confirm",
                            dest="action",
                            help=_("Ask the remote user to confirm or abort, then print the result."))
    parser.add_option("-C", "--checkauth",
                            dest="checkauth",
                            help=_("When --ask is used, if both an username and password are asked to the end user, pknotify tries to authenticate these username and password through PAM. If this is successful, both 'AUTH=YES' and 'USERNAME=theusername' are printed. If unsuccessful, 'AUTH=NO' is printed. Finally, if one field is missing, 'AUTH=IMPOSSIBLE' is printed."))
    parser.add_option("-D", "--denyafter",
                            type="int",
                            action="callback",
                            callback=checkandset_positiveint,
                            default=1,
                            dest="denyafter",
                            help=_("When --checkauth is used, this option tell pknotify to loop up to this value times or until the password is correct for the returned username. If authentication was impossible with the username and password received from the remote user, 'DENY' is printed, rejecting the print job. The default value is %default, meaning pknotify asks a single time."))
    parser.add_option("-d", "--destination",
                            dest="destination",
                            help=_("Indicate the mandatory remote hostname or IP address and optional TCP port where PyKotIcon is listening for incoming connections from pknotify. If not specified, the port defaults to 7654."))
    parser.add_option("-n", "--notify",
                            action="store_const",
                            const="notify",
                            dest="action",
                            help=_("Send an informational message to the remote user."))
    parser.add_option("-N", "--noremote",
                            dest="noremote",
                            default="CANCEL",
                            help=_("Tell pknotify what to print if it can't connect to a remote PyKotIcon application. The default value is 'CANCEL', which tells PyKota to cancel the print job. The only other supported value is 'CONTINUE', which tells PyKota to continue the processing of the current job."))
    parser.add_option("-q", "--quit",
                            dest="quit",
                            help=_("Ask the remote PyKotIcon application to quit. When combined with other command line options, any other action is performed first."))
    parser.add_option("-t", "--timeout",
                            type="int",
                            action="callback",
                            callback=checkandset_positiveint,
                            default=0,
                            dest="timeout",
                            help=_("Ensure that pknotify won't wait more than timeout seconds for an answer from the remote user. This avoids end users stalling a print queue because they don't answer in time. The default value is %default, making pknotify wait indefinitely."))
    run(parser, PyKotaNotify)

"""
  arguments :

    -a | --ask : Several arguments are accepted, of the form
                 "label:varname:defaultvalue". The result will
                 be printed to stdout in the following format :
                 VAR1NAME=VAR1VALUE
                 VAR2NAME=VAR2VALUE
                 ...
                 If the dialog was cancelled, nothing will be
                 printed. If one of the varname is 'password'
                 then this field is asked as a password (you won't
                 see what you type in), and is NOT printed. Although
                 it is not printed, it will be used to check if
                 authentication is valid if you specify --checkauth.

    -c | --confirm : A single argument is expected, representing the
                     message to display. If the dialog is confirmed
                     then pknotify will print OK, else CANCEL.

    -n | --notify : A single argument is expected, representing the
                    message to display. In this case pknotify will
                    always print OK.

examples :

  pknotify -d client:7654 --noremote CONTINUE --confirm "This job costs 10 credits"

  Would display the cost of the print job and asks for confirmation.
  If the end user doesn't have PyKotIcon running and accepting connections
  from the print server, PyKota will consider that the end user accepted
  to print this job.

  pknotify --destination $PYKOTAJOBORIGINATINGHOSTNAME:7654 \\
           --checkauth --ask "Your name:username:" "Your password:password:"

  Asks an username and password, and checks if they are valid.
  NB : The PYKOTAJOBORIGINATINGHOSTNAME environment variable is
  only set if you launch pknotify from cupspykota through a directive
  in ~pykota/pykota.conf

  The TCP port you'll use must be reachable on the client from the
  print server.
"""

"""
        defaults = { \
                     "timeout" : 0,
                     "noremote" : "CANCEL",
                   }
        short_options = "vhd:acnqCD:t:N:"
        long_options = ["help", "version", "destination=", "denyafter=", \
                        "timeout=", "ask", "checkauth", "confirm", "notify", \
                        "quit", "noremote=" ]

        elif (options["ask"] and (options["confirm"] or options["notify"])) \
             or (options["confirm"] and (options["ask"] or options["notify"])) \
             or ((options["checkauth"] or options["denyafter"]) and not options["ask"]) \
             or (options["notify"] and (options["ask"] or options["confirm"])) :
            raise PyKotaCommandLineError, _("incompatible options, see help.")
        elif (not options["destination"]) \
             or not (options["quit"] or options["ask"] or options["confirm"] or options["notify"]) :
            raise PyKotaCommandLineError, _("some options are mandatory, see help.")
        elif options["noremote"] not in ("CANCEL", "CONTINUE") :
            raise PyKotaCommandLineError, _("incorrect value for the --noremote command line switch, see help.")
        elif (not args) and (not options["quit"]) :
            raise PyKotaCommandLineError, _("some options require arguments, see help.")
"""
