import argparse
import getpass
import os
import sys

from passgeny import passgeny

pargs = argparse.ArgumentParser("Passgeny - Not a Passowrd Manager")
pargs.add_argument("domain", help="Domain or unique site identifier")
pargs.add_argument("user", help="Username or unique user identifier")
pargs.add_argument("tokens", nargs='*', help="Additional tokens")
pargs.add_argument("--verbose", "-v", action='store_true', help="Verbose")
pargs.add_argument("--pattern", "-p", help="Set pattern")

pargs_pass = pargs.add_mutually_exclusive_group()
pargs_pass.add_argument("--stdin", "-s", action='store_true', help="Read password from stdin")
pargs_pass.add_argument("--env", "-e", help="Read password from environment")

popt = pargs.parse_args()

# Read master password
if popt.env:
    mpw = os.getenv(popt.env)
    if mpw is None:
        raise Exception("Environment {} not defined.".format(popt.env))
elif popt.stdin:
    mpw = sys.stdin.readline().rstrip('\n\r')
else:
    mpw = getpass.getpass("Master password: ")

pg = passgeny.Passgeny(mpw)
del mpw

if popt.pattern:
    pg.set_pattern(popt.pattern)

print(pg.generate(popt.domain, popt.user, *popt.tokens))
