#! /usr/bin/env python

# These commands were used to create the loops
# losetup -e AES128 /dev/loop0 /e/work-urd
# losetup -d /dev/loop0
# losetup -e AES128 /dev/loop1 /e/pagefile
# losetup -d /dev/loop1

def GetPassword():
    """The loop-aes requires a long poassword that I don't want to
    remember or type, so I combine password with a predetermined salt
    to create the real password"""

    import getpass, sha, sys

    salt = 'obscured'

    password = getpass.getpass("Password: ")
    m = sha.new()
    m.update(salt)
    m.update(password)

#     if m.hexdigest() == real: print "yahoo!"
    return m.hexdigest()

def TestPartitions(partition):
    """ Test if the partitions are already mounted, if not do so"""

    import commands, getpass, os, sha

    ssh = None
    password = None

    if os.listdir(partition) == []: # not mounted
        password = GetPassword()
        MountPartition(password,ssh,partition)
    else: print "Local %s already mounted" % partition

#     if commands.getstatusoutput('ssh policy test -d %partition; pmount=$?; echo $pmount' %s)[1] == '1':
#         ssh=1
#         if not password: password = GetPassword()
#         MountPartition(password,ssh)
#     else: print "Remote already mounted"

def MountPartition(password,ssh,partition):

    import os, pexpect, sys
    if not ssh:
        print "LOCALLY Mounting %s" % partition,
        child = pexpect.spawn('mount %s' % partition)
#     else:
#         print "REMOTELY Mounting",
#         child = pexpect.spawn('ssh policy.w3.org bctool mount -t ext3 /e/work-policy /home/reagle/data')
    result = child.expect(['Password:','Error:.*',pexpect.EOF], 5)
    if result == 0:
        child.sendline(password)
        presult = child.expect(['mount:.*',pexpect.EOF], 5)
        if presult == 0:
            print "Password incorrect"
            sys.exit()
        elif presult == 1:
            print "Successfully mounted"
        else:
            print "Exited in unknown state"
    elif result == 1:
        print "Some sort of error"
    elif result == 2:
        print "Successfully mounted"
    else:
        print "Exited in unknown state"


#Check to see if the script is executing as main.
if __name__ == "__main__":
   ## Parse the command line arguments for optional message and files.


    import getopt, sys
    message = None
    partition = '/home/reagle/data'

    try:
        options, arguments = getopt.getopt (sys.argv[1:],"wj")
    except getopt.error:
        print 'Error: Unknown option or missing argument.'
    for opt, val in options:
        if opt == '-j':
            print opt, "pagefile"
            partition = '/x'
        elif opt == '-w': 
            print opt, "work"
            partition = '/home/reagle/data'
    TestPartitions(partition) 
