#!/usr/bin/env python
''' 
USAGE:  gpchangeuserpassword --user USER --password PASSWORD
        where USER is the user for whom the password is being changed
        where PASSWORD is the new password
'''

import os, sys, getpass, crypt
from subprocess import Popen
sys.path.append(sys.path[0] + '/../bin/lib')

try:
    import pexpect
    from optparse import Option, OptionParser 
    from gppylib.gpparseopts import OptParser, OptChecker
    from gppylib.commands.unix import SYSTEM
except ImportError, e:    
    sys.exit('Cannot import modules.  Please check that you have sourced greenplum_path.sh.  Detail: ' + str(e))

options = None

parser = OptParser(option_class=OptChecker)
parser.remove_option('-h')
parser.add_option('-h', '-?', '--help', action='store_true')
parser.add_option('-u', '--user', type='string')
parser.add_option('-p', '--password', type='string')
(options, args) = parser.parse_args()

global gphome
gphome = os.environ.get('GPHOME')
if not gphome:
    sys.stderr.write("GPHOME not set\n")
    sys.exit(1)

if options.help:
    sys.stderr.write(__doc__)
    sys.exit(0)

if not options.user:
    sys.stderr.write("--user must be specified\n")
    sys.exit(1)

if not options.password:
    sys.stderr.write("--password must be specified\n")
    sys.exit(1)

if options.user == "root":
    sys.stderr.write("root password can not be changed with this utility\n")
    sys.exit(1)

if getpass.getuser() != "root":
    sys.stderr.write("this utility must be run as root\n")
    sys.exit(1)

####################################################################################################
if SYSTEM.getName() == "linux":

    cmdstr = 'usermod -p "%s" %s' % (crypt.crypt(options.password, options.password), options.user)
    p = Popen(cmdstr, shell=True, executable="/bin/bash")
    sts = os.waitpid(p.pid, 0)[1]
    if sts:
        sys.stderr.write("error on cmd: %s\n" % cmdstr)
        sys.exit(1)
    else:
        sys.exit(0)
####################################################################################################

if SYSTEM.getName() != "sunos":
    sys.stderr.write("linux and solaris are the only operating systems supported by this utility\n")
    sys.exit(1)

# SOLARIS password change
# New Password:
# Re-enter new Password:
# passwd: They don't match.
# passwd: password successfully changed for ivanfoo

done = False
child = None

try:
    cmdstr = "passwd %s" % options.user
    child = pexpect.spawn(cmdstr)

    index = 0
    while 1:
        index = child.expect(["match", "success", "Password", pexpect.EOF, pexpect.TIMEOUT])
        if index == 0:
            sys.stderr.write("passwords did not match\n")
            sys.exit(1)
        elif index == 1:
            child.close
            sys.exit(0)
        elif index == 2:
            child.sendline(options.password)
            continue
        elif index == 3:
            sys.stderr.write("error calling passwd\n")
            sys.exit(1)
        elif index == 4:
            sys.stderr.write("timeout calling passwd\n")
            sys.exit(1)
        else:
            sys.stderr.write("error2 calling passwd\n")
            sys.exit(1)

except Exception, e:
    sys.stderr.write("Exception running cmd: %s\n" % cmdstr)
    sys.stderr.write("%s\n" % e.__str__())
    sys.exit(1)
