#! /usr/bin/python
#
#
# Define a main function to allow for function declaration in any order.
# The main program lives in the main function.
def main():
  # System modules
  import sys
  import re
  import string
  import commands
  # Local modules (must live in the same directory).
  import ciab_user_functions as cuf
  from ciab_common_vars import (commonVariables)
  #
  # Variables
  nodeNumberString = ''
  nodeAddress      = ''
  templatesDir     = ''
  templatesDirName = '/../templates'
  
  # Yep, the final comma is correct: it's a list of variables!
  nodeNumberString, = usage(sys.argv)
  # Must be all digits.
  if re.match("\D", nodeNumberString):
    print 
    print
    print sys.argv[0], ': invalid node number "', nodeNumberString, '".'
    print 'Aborting!'
    print
    print
    sys.exit(1)
  # Make sure the number is whithin the limits.
  if int(nodeNumberString) >= int(commonVariables['COMPUTE_NODE_MAX_NUM']):
    print 
    print
    print sys.argv[0], ': invalid node number "', nodeNumberString, '".'
    print 'Must be <', commonVariables['COMPUTE_NODE_MAX_NUM'], '.'
    print 'Aborting!'
    print
    print
    sys.exit(1)
  
  # Nomalize to three digits.
  while len(nodeNumberString) < 3:
    nodeNumberString = '0' + nodeNumberString
  print 'Node number string: ', nodeNumberString
  
  currentNodeName = commonVariables['COMPUTE_NODE_NAME_PREFIX'] + \
                    nodeNumberString
  # Get the templates directory.
  templatesDir = commands.getoutput('dirname ' + sys.argv[0]) + templatesDirName  
  
  # Check if the virtual machine we want to build is not already running.
  isRunning = commands.getoutput('xm list | grep ' + currentNodeName)
  #isRunning = commands.getoutput('xm list | grep ' + 'compute-node-model')
  if isRunning != '':
    print
    print
    print sys.argv[0], ': VM "', currentHostName, '" is already running.'
    print 'Aborting!'
    print
    print
    sys.exit(1)
  # Create the VM system disk (a snapshot of the compute node model disk).
  computeNodeSystemDisk = commonVariables['SYSTEM_DISK_CLONE_PREFIX'] + \
                          nodeNumberString + \
                          commonVariables['SYSTEM_DISK_CLONE_POSTFIX']
  commandString = 'lvcreate -L ' + commonVariables['SYSTEM_DISK_CLONE_SIZE'] + \
                          ' -s ' +\
                          ' -n ' + computeNodeSystemDisk + \
			     ' ' + commonVariables['SYSTEM_DISK_MASTER']
  #print commandString
  status = 0
  # FIXME!!!!!!!!!!!!!!!!!!!!!
  #status,output = commands.getstatusoutput(commandString)
  if status != 0 :
    print
    print
    print sys.argv[0], ': could not create VM system disk.'
    print output
    print 'Aborting!'
    print
    print
    sys.exit(1)
  # Create the VM swap volume
  computeNodeSwapDisk = commonVariables['SWAP_DISK_PREFIX'] + \
                        nodeNumberString + \
                        commonVariables['SWAP_DISK_POSTFIX']
  print computeNodeSwapDisk
  commandString = 'lvcreate -L ' + commonVariables['SWAP_DISK_SIZE'] + \
                          ' -n ' + computeNodeSwapDisk + \
			     ' ' + commonVariables['SWAP_DISK_LOGICAL_VOLUME']
  print commandString
  # FIXME!!!!!!!!!!!!!!!!!!!!!
  #status,output = commands.getstatusoutput(commandString)
  if status != 0 :
    print
    print
    print sys.argv[0], ': could not create the VM swap disk.'
    print output
    print 'Aborting!'
    print
    print
    sys.exit(1)
  commandLine = 'mkswap ' + commonVariables['SWAP_DISK_LOGICAL_VOLUME'] + \
                '/' + computeNodeSwapDisk
  print commandString
  # FIXME!!!!!!!!!!!!!!!!!!!!!
  #status,output = commands.getstatusoutput(commandString)
  if status != 0 :
    print
    print
    print sys.argv[0], ': could not format the VM swap disk.'
    print output
    print 'Aborting!'
    print
    print
    sys.exit(1)
  # Mount the VM system disk to copy all the specific files
  commandString = 'mount ' + commonVariables['SYSTEM_DISK_LOGICAL_VOLUME'] + \
                             '/' + computeNodeSystemDisk + ' ' + \
                             commonVariables['COMPUTE_NODE_DISK_MOUNT_POINT']
  print commandString
			   
  # FIXME!!!!!!!!!!!!!!!!!!!!!
  #status,output = commands.getstatusoutput(commandString)
  if status != 0 :
    print
    print
    print sys.argv[0], ': could not mount the VM system disk.'
    print output
    print 'Aborting!'
    print
    print
    sys.exit(1)
  
  # /etc/network/interfaces
  currentFile = '/etc/network/interfaces'
  commandString = 'cp ' + templatesDir + currentFile + ' ' +\
                   commonVariables['COMPUTE_NODE_DISK_MOUNT_POINT'] + \
		   currentFile
  print commandString
  nodeAddress = commonVariables['COMPUTE_NODE_STATIC_NETWORK_PREFIX'] + '.' + \
                nodeNumberString
  commandString = 'rpl __STATIC_ADDRESS__ ' + nodeAddress + ' ' + \
                  commonVariables['COMPUTE_NODE_DISK_MOUNT_POINT'] 
#  cp templates$CURRENT_PATH/interfaces \
#   $COMPUTE_NODE_DISK_MOUNT_POINT/$CURRENT_PATH
#  ADDRESS="$COMPUTE_NODE_STATIC_NETWORK_PREFIX.$NODE_NUMBER"
#  rpl __STATIC_ADDRESS__ $ADDRESS  \
#    ${COMPUTE_NODE_DISK_MOUNT_POINT}${CURRENT_PATH}/interfaces

  print 'Current node name: ', currentNodeName
  print commonVariables.keys()
  print commonVariables.values()
# End main

def usage(arguments):
  import sys
  if (len(arguments) < 2):
    print
    print
    print 'Missing parameter. Aborting'
    print
    print 'Usage: ' + arguments[0] + ' node_number'
    print
    print
    sys.exit(1)
  nodeNumberString = arguments[1]
  # Yep, the final comma is correct: it's a list of variables!
  return nodeNumberString,
  
if __name__ == "__main__":
  main()
