#!/usr/python

import os
import getpass
import sys
import getopt

#######
# ABOUT
#######
# SlaMBack.py

##########
# RELEASES
##########
# v1.0 - 2009-DEC-9 - Initial Release

###################
# KNOWN LIMITATIONS
###################
# 1. All of the SMB shares must use the same username/password combination.
# 2. The mount point directories must exist. The program will halt if it encounters a request to mount a
#    a folder that doesn't exist.
########################
# REQUIRED CONFIGURATION
########################
# username to connect to SMB shares
userName = '[ENTER USER NAME HERE]'
# the directory that will host your shares
homePath = '[EXAMPLE: /Users/bob/shares]'
# the list of SMB shares and where to mount them. NOTE: the mount point (folder) must exist on the local machine
shares = [
 'smbserverA/home/bob ~/shares/bob_home', 
 'smbserverB/public ~/shares/public'
]

########################
# OPTIONAL CONFIGURATION
########################
# password to connect to SMB shares. If it is empty, is will be prompted for.
password = ''

##########################
# DO NOT TOUCH BEYOND HERE
##########################
def doMount():
    global password

    if (password == ''):
        password = getpass.getpass("Enter password:")
            
    map(os.system, [('mount_smbfs //' + userName + ':' + password + '@' + shr)  for shr in shares])


def doUnmount():
    global homePath 
    homePath = CorrectPath(homePath)
 
    dirs = os.listdir(homePath)

    for s in dirs:
        isMounted = os.path.ismount(homePath + s)
        if isMounted == True:
            os.system('umount ' + homePath + s)

def usage():
    usage = """Usage: slamback.py [-hu]
  If no operands are given, the configured shares will be mounted.

  The following options are available:

  -h --help         Displays this help
  -u --unmount      Unmount all shares 
    """

    print usage

def CorrectPath(path):
    if path[len(path) - 1:] != '/':
        return path + '/'
    else:
        return path

def main(argv):
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hu", ["help", "unmount"])
    except getopt.GetoptError, err:
        usage()
        sys.exit(2)

    if len(opts) > 0:
        for opt, arg in opts:
            if opt in ('-h', '--help'):
                usage()
                sys.exit()
            elif opt in ('-u', '--unmount'):
                doUnmount()
    else:
        doMount()


if __name__ == "__main__":
    main(sys.argv[1:])





