#!/usr/bin/python
##
## SecurePass CLI tools utilities
## Change/disable user's password
##
## (c) 2013 Giuseppe Paterno' (gpaterno@gpaterno.com)
##          GARL Sagl (www.garl.ch)
##


from securepass import utils
from securepass import securepass
import getpass
import logging
from optparse import OptionParser


parser = OptionParser(usage="""Change/disable user password for SecurePass

%prog [options] userid""")


parser.add_option('-D', '--debug',
                  action='store_true', dest="debug_flag",
	              help="Enable debug output",)

parser.add_option('-d', '--disable',
                  action='store_true', dest="disable_flag",
	              help="Disable user's password",)


opts, args = parser.parse_args()

## Set debug
FORMAT = '%(asctime)-15s %(levelname)s: %(message)s'
if opts.debug_flag:
    logging.basicConfig(format=FORMAT, level=logging.DEBUG)
else:
    logging.basicConfig(format=FORMAT, level=logging.INFO)


## Load config
config =  utils.loadConfig()

## Config the handler
sp_handler = securepass.SecurePass(app_id=config['app_id'],
                                   app_secret=config['app_secret'],
                                   endpoint=config['endpoint'])

## Check user exists
try:
    if args[0].strip() == "":
        print "Missing username. Try with --help"
        exit(1)
except IndexError:
    print "Missing username. Try with --help"
    exit(1)


## If we ask for disable password
if opts.disable_flag:
    try:
        sp_handler.user_password_disable(args[0].strip())
        print "Password removed."
        exit(0)
    except Exception as e:
        print e
        exit(1)

## if we ask for change password
else:
    password = getpass.getpass()
    verifypw = getpass.getpass(prompt='Verify Password: ')

    ## if matches
    if password == verifypw:
        try:
            sp_handler.user_password_change(user=args[0].strip(), password=password)
            print "Password changed."
            exit(1)
        except Exception as e:
            print e
            exit(1)

    else:
        print "Passwords don't match!"
        exit(1)

