#!python

#
#   $ aletheia generate
#   $ aletheia sign /path/to/file public-key-url
#   $ aletheia verify /path/to/file
#

import argparse
import os
import sys

from aletheia.aletheia import Aletheia
from aletheia.utils import generate, sign, verify


class Command:

    def __init__(self):

        parser = argparse.ArgumentParser(prog="aletheia")
        parser.set_defaults(func=parser.print_help)
        subparsers = parser.add_subparsers(dest="subcommand")

        subparsers.add_parser(
            "generate",
            help="Generate a public/private key pair for use in siging & 3rd "
                 "party verification. (Do this first)"
        )

        parser_sign = subparsers.add_parser("sign", help="Sign a file")
        parser_sign.add_argument("path")
        parser_sign.add_argument("url")

        parser_verify = subparsers.add_parser(
            "verify", help="Verify the origin of a file")
        parser_verify.add_argument("path")

        args = parser.parse_args()

        try:
            if args.subcommand:
                getattr(self, args.subcommand)(args)
            else:
                parser.print_help()
        except (RuntimeError, FileNotFoundError) as e:
            print(e, file=sys.stdout)
            sys.exit(1)

        sys.exit(0)

    @classmethod
    def generate(cls, *args):

        private = os.path.join(Aletheia.HOME, "aletheia.pem")
        if os.path.exists(private):
            print(
                "It looks like you already have a key setup at {}.\n"
                "Exiting prematurely just to be safe.".format(private)
            )
            sys.exit(1)

        print("Generating private/public key pair...")
        generate()
        print("""
            All finished!

            You now have two files: aletheia.pem (your private key) and
            aletheia.pub (your public key).  Keep the former private, and share
            the latter far-and-wide.  Importantly, place your public key at a
            publicly accessible URL so that when you sign a file with your
            private key, it can be verified by reading the public key at that
            URL.
        """.replace("            ", ""))

    @classmethod
    def sign(cls, args):
        print("Signing {} with your private key".format(args.path))
        sign(args.path, args.url)
        sys.exit(0)

    @classmethod
    def verify(cls, args):

        if verify(args.path):
            print("The file appears to be legit")
            sys.exit(0)

        print("There's something wrong with that file")
        sys.exit(1)



if __name__ == "__main__":
    Command()
