import client
import message
import config
import util
import tempfile
import subprocess
import os

known_messages = message.messagestore(config.MSGDIR)

first_help = True

while True:
    print()
    x = input("> ").split(" ")
    command, arguments = x[0], x[1:]
    if command == "sync":
        if len(arguments) == 2:
            client.sync(arguments[0], int(arguments[1]))
        elif len(arguments) == 1:
            client.sync(arguments[0])
        elif len(arguments) == 0:
            client.sync("localhost")

    elif command == "ls":
        for msgid in known_messages.keys():
            print(util.tohex(msgid))

    elif command == "help" and len(arguments) == 0:
        if first_help:
            print("Square brackets indicate optional arguments")
            print("A default is given for some commands")
            print("")
            first_help = False
        print("sync [IP = localhost] [PORT = 3514]")
        print("ls")
        print("help")

    elif command == "msg":
        recipients = arguments
        if len(recipients) == 0:
            print("Enter email addresses one by one for recipients")
            print("These must be the same as GPG knows them as")
            print("The above is very important, you might want to run")
            print("    gpg --list-keys")
            print("To make sure you're using the correct email")
            print("There is currently no error checking for invalid input")
            print()
            print("Enter a blank line to end input")
            while True:
                r = input("email: ")
                if r == "":
                    break
                recipients.append(r.strip())

        data = util.getinput()
        program = ["gpg", "--encrypt", "--sign"]
        for r in recipients:
            program.append("-r")
            program.append(r)
        encsign = subprocess.check_output(program, input=data.encode("UTF-8"))

        newmsg = message.message(encsign)
        known_messages[newmsg.msgid] = newmsg
        print("ID: {}".format(util.tohex(newmsg.msgid)))
        print("Message added to known messages")
        print("Run a sync against a known node, or wait for the syncd to run")

    elif command == "attach":
        recipients = arguments[:-1]
        fname = arguments[-1]
        with open(fname, "rb") as f:
            data = f.read()
        program = ["gpg", "--encrypt", "--sign"]
        for r in recipients:
            program.append("-r")
            program.append(r)
        encsign = subprocess.check_output(program, input=data)
        newmsg = message.message(encsign)
        known_messages[newmsg.msgid] = newmsg
        print("ID: {}".format(util.tohex(newmsg.msgid)))
        print("Attachment added to known messages")
        print("Run a sync against a known node, or wait for the syncd to run")

    elif command == "read":
        if len(arguments) == 0:
            print("What do you want me to read?")
        else:
            foundmsgs = []
            wantedhex = arguments[0]
            if not(wantedhex.startswith("0x")):
                wantedhex = "0x" + wantedhex
            wantedhex = wantedhex.encode("ascii")

            for msgid in known_messages.keys():
                msgidhex = util.tohex(msgid)
                if msgidhex.startswith(wantedhex.decode("ascii")):
                    foundmsgs.append(msgid)

            if len(foundmsgs) > 1:
                print("More than one message found, be more specific")
            elif len(foundmsgs) == 0:
                print("No messages found")
            else:
                msg = known_messages[foundmsgs[0]].gpg
                decrypted = subprocess.check_output("gpg",
                                                    input=msg,
                                                    stderr=subprocess.DEVNULL
                                                    )
                try:
                    decrypted = decrypted.decode("UTF-8")
                    util.writeoutput(decrypted)
                except UnicodeDecodeError:
                    # Likely a binary file.
                    print("The file can't be decoded, likely an attachment.")
                    print("Enter a filename to save it as")
                    fname = input("fname: ")
                    with open(fname, "wb") as f:
                        f.write(decrypted)

    else:
        print("Unknown command")

@@ -761,24 +761,88 @@
 arguments%22)%0A
+            print(%22Angle brackets indicate required arguments%22)%0A
             
@@ -1032,16 +1032,1317 @@
 nt(%22help
+ %5BCOMMAND%5D%22)%0A        print(%22msg %5Brecipients%5D%22)%0A        print(%22attach %5Brecipients%5D %3Cfilename%3E%22)%0A        print(%22read %3Cmsgid%3E%22)%0A    elif command == %22help%22 and len(arguments) %3E 0:%0A        helpcmd = arguments%5B0%5D%0A%0A        if helpcmd == %22sync%22:%0A            print(%22Push and pull all your currently known messages to the%22)%0A            print(%22specified server. With no arguments, sync with own daemon%22)%0A            print(%22which won't do anything, but is good for debugging.%22)%0A%0A        elif helpcmd == %22ls%22:%0A            print(%22List all known messages by their msgid. Does not filter%22)%0A            print(%22for if you can actually read them at the moment%22)%0A%0A        elif helpcmd == %22help%22:%0A            print(%22You're using it now.%22)%0A%0A        elif helpcmd == %22attach%22:%0A            print(%22Allows you to insert binary files to the network.%22)%0A            print(%22Currently there are no restrictions, but obviously%22)%0A            print(%22inserting a 4GB file will be slow, and in the future%22)%0A            print(%22nodes may reject large files, or delete them sooner.%22)%0A%0A        elif helpcmd == %22read%22:%0A            print(%22Read the message specified by the msgid.%22)%0A            print(%22Partial ids are supported, with/without the 0x prefix.%22)%0A%0A        elif helpcmd == %22msg%22:%0A            print(%22Write textual messages in an editor
 %22)%0A%0A    

Improve help messages