#!/usr/bin/env python
'''
This file is part of the Python EJTP library.

The Python EJTP library is free software: you can redistribute it 
and/or modify it under the terms of the GNU Lesser Public License as
published by the Free Software Foundation, either version 3 of the 
License, or (at your option) any later version.

the Python EJTP library 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 Lesser Public License for more details.

You should have received a copy of the GNU Lesser Public License
along with the Python EJTP library.  If not, see 
<http://www.gnu.org/licenses/>.
'''

__doc__ = '''ejtp-crypto

A simple little script for run EJTP encryptors from the command line.

Usage:
    ejtp-crypto ( encode | decode | sign ) ( id | with ) <parameter> [-f <filename>]
    ejtp-crypto ( sig-verify ) ( id | with ) <parameter> --sigfile=<sigfile> [-f <filename>]
    ejtp-crypto -h | --help
    ejtp-crypto --version

Options:
    -f <filename>   File used as stdin
    -h --help       Show this help message
'''

import sys
import binascii

from persei import String

from ejtp.vendor.docopt import docopt
from ejtp.crypto.encryptor import make
from ejtp.identity.cache import IdentityCache
from ejtp.config import configure_identity_cache

def byte_to_hex(bytestr):
    return binascii.hexlify(bytestr).decode('ascii')

def hex_to_byte(hexstr):
    return binascii.unhexlify(hexstr.encode('ascii'))

def main(argv=None):
    arguments = docopt(__doc__, argv=argv[1:],
        version='ejtp-crypto 0.9.7')

    if arguments['-f']:
        with open(arguments['-f'], 'r') as stdin:
            input_text = stdin.read()
    else:
        input_text = sys.stdin.read()

    input_text = input_text.rstrip('\n')

    encryptor = None
    if arguments['id']:
        cache = IdentityCache()
        configure_identity_cache(cache)
        identity = cache.find_by_name(arguments['<parameter>'])
        encryptor = identity.encryptor
    if arguments['with']:
        encryptor = make(String(arguments['<parameter>']))

    if arguments['encode']:
        encrypted = encryptor.encrypt(input_text)
        print(byte_to_hex(encrypted.export()))
    if arguments['decode']:
        decrypted = encryptor.decrypt(hex_to_byte(input_text))
        print(decrypted.export().decode('utf-8'))
    if arguments['sign']:
        print(byte_to_hex(encryptor.sign(input_text).export()))
    if arguments['sig-verify'] and arguments['--sigfile']:
        sigfile = arguments['--sigfile']
        with open(sigfile) as f:
            signature = hex_to_byte(f.read().rstrip())
            print(encryptor.sig_verify(input_text, signature))

if __name__ == '__main__':
    main(sys.argv)

