# Time-stamp: <2001-11-08 15:02:07 crabbkw>

# Code and design by Casey Crabb (crabbkw@rose-hulman.edu)
# This code is licensed under the BSD license.
# See the LICENSE file for details
#
# Copyright Casey Crabb (crabbkw@rose-hulman.edu) July 2001
#



try:
    from xml.parsers import expat
except:
    from xml.parsers import pyexpat
    expat = pyexpat
import os
import string
import sys
import getpass
import socket
from JabberHandler import JabberContentHandler

class AccountCreator:
    def __init__(self, server, user, password, resource, writeconfig=1, callback=None):
        self.server=server
        self.user=user
        self.password=password
        self.resource=resource
        self.debug = 0
        self.oncethrough = 0
        self.writeconfig = writeconfig
        self.callback = callback

    def handleStream(self, stream):
        id = stream.id
        tosend = "<iq type='get'><query"\
                 " xmlns='jabber:iq:register'/></iq>"
        self.sendPacket(tosend)

    def handleIQ(self, iq):
        type = iq.type
        if(type == "error"):
            print "Error! Try a different username"
            sys.exit(-1)
        if(self.oncethrough and type == "result"):
            if(self.writeconfig):
                self.writeConfig()
            self.disconnect()
            return
        key = None
        try:
            key = iq.query.key.text
        except:
            pass
        if(key):
            tosend = "<iq type='set'><query"\
                     " xmlns='jabber:iq:register'>"\
                     "<key>"+key+"</key>"\
                     "<username>"+self.user+"</username>"\
                     "<password>"+self.password+"</password>"\
                     "</query></iq>"
        else:
            tosend = "<iq type='set'><query"\
                     " xmlns='jabber:iq:register'>"\
                     "<username>"+self.user+"</username>"\
                     "<password>"+self.password+"</password>"\
                     "</query></iq>"
        self.oncethrough = 1
        self.sendPacket(tosend)

    def connect(self):
        self.mainSocket = socket.socket(socket.AF_INET,
                                        socket.SOCK_STREAM)
        self.mainSocket.connect((self.server,5222))
        self.jch = JabberContentHandler(self, 0)
        self.jch.debug = 0
        self.sendPacket("<stream:stream to='"+self.server+
                        "' xmlns='jabber:client' "+
                        "xmlns:stream='http://etherx.jabber.org/streams'>")
        # self.jch.setDaemon(1)
        self.jch.start()

    def writeConfig(self):
        towrite = "<imcom default='"+self.server+"'>\n"\
                  "    <profile name='"+self.server+"' debug='false' "\
                  "statusshow='true' ssl='false' colors='true' "\
                  "ringbell='true'>\n"\
                  "        <server>"+self.server+"</server>\n"\
                  "        <port>5222</port>\n"\
                  "        <user>"+self.user+"</user>\n"\
                  "        <password>"+self.password+"</password>\n"\
                  "        <resource>"+self.resource+"</resource>\n"\
                  "    </profile>\n"\
                  "</imcom>"
        confirm = raw_input("Ready to write ~/.imcom/imcomrc proceed? "\
                            "(yes/no)> ")
        if(confirm and string.lower(confirm) == "yes"):
            try:
                os.mkdir(os.environ['HOME']+"/.imcom",0700)
            except:
                pass
            try:
                f = open(os.environ['HOME']+"/.imcom/imcomrc","w")
                f.write(towrite)
                f.flush()
                f.close()
                print
                print "You can now run python CLI.py and log on with your account!"
            except:
                print "There was an error: "
                print str(sys.exc_info()[0])
                print str(sys.exc_info()[1])
                print "In the likely case that you're out of diskspace I'll "\
                      "display the config file so you can copy paste it."
                print towrite
        else:
            print "The account was created, however, your "\
                  "configuration was not written to file at your "\
                  "request. You can create the config on your own "\
                  "and it will work."

    def disconnect(self):
        print "disconnecting"
        self.closeSocket()
        if(self.callback != None):
            print "calling callback"
            self.callback.OnCallback(None)
        #self.sendPacket("</stream:stream>")

    def handleDisconnected(self):
        return

    def closeSocket(self):
        self.jch.running = 0
        self.mainSocket.close()
        self.mainSocket = None

    def sendPacket(self, text):
        if(self.debug):
            print "sending :> " + text
        self.mainSocket.send(text)

if(__name__ == "__main__"):
    print("This utility will create an account for you on a jabber server.")
    print("It will also create an initial ~/.imcom/imcomrc file for you.")
    print("Warning: This program will overwrite ~/.imcom/imcomrc.")

    print
    print("If you're not sure what jabber server you want to use,"\
          " use jabber.org")
    server = raw_input("Enter a server name: ")

    print
    print("Enter your desired username below. ")
    user   = raw_input("Enter your username: ")

    print
    print("Enter your password below.")
    password = getpass.getpass()

    print
    print("Enter the resource below. The resource is typically where"\
          "you are using jabber from (home, work, etc) it can be any"\
          "string. It cannot be NULL.")
    resource = raw_input("Enter a resource: ")
    if(resource == None):
        resource = "IMCom"

    #name = raw_input("Enter your name: ")
    #email = raw_input("Enter your email: ")

    # now create the account
    AC = AccountCreator(server,user,password,resource)
    AC.connect()
