#!/usr/local/bin/python --

"""
makemachine2.py <install|normal>
  Install turns on drive formatting (which isn't implemented)." 

  Example: ./makeMachine.py normal

"""

import os, sys, string, time, getopt
import socket
import commands


gDatabase = {}
gMountedSony = 0

def usage(progname):
  print "usage: %s" % progname
  print __doc__

def hostnamePrep():
  # Attempt to get the hostname
  f = open('/etc/dhcpc/hostinfo-eth0', 'r')

  lines = f.readlines()
  f.close()
  for line in lines:
    line = line[:-1]		# Remove the newline at the end
    if string.find(line, 'IPADDR') == 0:
      (tmp,ip) = string.split(line, '=')

  (iphost, tmp, tmp) = socket.gethostbyaddr(ip)

  f = os.popen('/bin/hostname', 'r')
  lines = f.readlines()
  f.close()
  for line in lines:
    host = line[:-1]		# Remove the newline at the end

  if (host == iphost):
    print "Hostname already set ..."
    return host

  print " Do you want to change name from [%s] to [%s] ?" % (host, iphost)
  choice = raw_input("y/n :")
  if choice <> 'y':
    appExit(1, "Exiting. Not changing name.")

  r = os.system("/bin/hostname %s" % iphost)

  f = open('/etc/sysconfig/network', 'w')
  f.write('NETWORKING=yes\nFORWARD_IPV4=false\nHOSTNAME=%s\n' % iphost)
  f.close()

  print "Hostname is now set ... please reboot to set properly"
  

  if r != 0:
    appExit(1, "Exiting. Something went wrong when trying to change name.")

  return iphost


def egroupsPrep():

  global gMountedSony

  # Make sure there is a directory for us

  if not os.path.exists('/egroups/Ops/Setup'):
    r = os.system('/usr/bin/install -g 0 -o 0 -m 755 -d /egroups/Ops/Setup')
    print "Setting up /egroups/Ops/Setup directory..."
    if r != 0:
      appExit(1, "Exiting. Could not setup proper /egroups/Ops/Setup directory.")

  print "Setup /egroups/Ops/Setup directory..."

  # Now handle the mount of sony
  if not os.path.exists('/egroups/tmpSony'):
    r = os.system('/usr/bin/install -g 0 -o 0 -m 755 -d /egroups/tmpSony')
    if r != 0:
      appExit(1, "Exiting. Could not setup proper /egroups/tmpSony directory.")

  print "Mounted /egroups/tmpSony directory..."

  r = os.system('/bin/mount 10.1.1.6:/  /egroups/tmpSony')
  if r != 0:
    print "Exiting. Could not mount Sony to /egroups/tmpSony directory."

  gMountedSony = 1


def readDb():
  global gDatabase
  # Attempt to get the hostname
  f = open('/egroups/tmpSony/root/MachSetup/Machine.db', 'r')
  data = f.read()
  f.close()
  gDatabase = eval(data)
  return


def appExit(errorCode, message):
  global gMountedSony
  
  print message

  if gMountedSony == 0:
    sys.exit(errorcode)

  r = os.system('/bin/umount /egroups/tmpSony')
  if r != 0:
    print "Exiting. Couldn't unmount /egroups/tmpSony." 
    sys.exit(1)

  sys.exit(0)

  
def duh():
  #
  x = os.system("newfs /dev/rwd%ss1a" % (disk))
  if x != 0:
    print "An error occured while doing 'newfs'"
    sys.exit(1)

  # Recurse once into this same routine to cause the mount to occur
  diskPrep(disk)

def diskCopy(disk):
  #
  # Test to see if this was already performed
  #
  if os.path.exists("/d1/tmp/MachineBuild"):
    print "Copy already done"
    return

  # Prepare for the dump/restore
  try:
    os.chdir("/d1")
  except:
    print "Couldn't chdir to /d1"
    print "x %s" % x
    sys.exit(1)

  print "\n\nLast chance. Go ahead with the dump/restore??"
  choice = raw_input("y/n :")
  if choice <> 'y':
    print "Exiting. Not formatting drive."
    sys.exit(1)

  # Do the dump restore
  x = os.system("dump -0f - / | restore -rf -")
  if x != 0:
    print "Dump restore failed"
    sys.exit(1)

  os.mkdir("/d1/tmp/MachineBuild", 0777)

def diskHostSetup(disk,hostname,ip):
  # Each setup portion will test if it was already performed

  #
  # Hostname and IP
  #
  if not os.path.exists("/d1/tmp/MachineBuild/rc"):
    file = open("/d1/etc/rc.conf.local", 'w')
    file.write("hostname=\"%s.egroups.com\"\n" % hostname)
    file.write("ifconfig_fxp0=\"inet 10.1.1.%s netmask 255.255.0.0\"\n" % ip)
    file.close()
    file = open("/d1/tmp/MachineBuild/rc", 'w')
    file.close()
  else:
    print "RC already done"

  #
  # Hosts file
  #
  if not os.path.exists("/d1/tmp/MachineBuild/hosts"):
    file = open("/d1/etc/hosts", 'w')
    file.write("127.0.0.1     localhost\n")
    file.write("10.1.1.%s     %s.egroups.com\n" % (ip, hostname))
    file.close()
    file = open("/d1/tmp/MachineBuild/hosts", 'w')
    file.close()
  else:
    print "Hosts already done"

  #
  # SSH file?
  #
  if not os.path.exists("/d1/tmp/MachineBuild/sshd"):
  # Do the dump restore
    os.unlink("/d1/etc/ssh_host_key")
    print "ssh-keygen -b 1024 -f /d1/etc/ssh_host_key -N "
    x = os.system("ssh-keygen -b 1024 -f /d1/etc/ssh_host_key -N '' ")
    if x != 0:
      print "ssh keygen failed"
      sys.exit(1)
    file = open("/d1/tmp/MachineBuild/sshd", 'w')
    file.close()
  else:
    print "sshd keygen already done"

def main(argv, stdout, environ):
  progname = argv[0]
  list, args = getopt.getopt(argv[1:], "", ["help"])

  if len(args) < 1:
    usage(progname)
    return
  for (field, val) in list:
    if field == "--help":
      usage(progname)
      return

  if os.geteuid() != 0:
    print "Sorry, you have to be the root user to run this program." 
    return


  if args[0] == 'install':
    mode = 'install'
  elif args[0] == 'normal':
    mode = 'normal'
  else:
    usage(progname)
    sys.exit(1)


#  drive =  args[0]
#  name  =  args[1]
#  ip    =  args[2]

#  if drive == 0:
#    print "Cannot be drive 0. That is the master"
#    sys.exit(1)

  #
  # Take the time
  #
  start = time.time()

  #
  # First - prep the disk
  #
  host = hostnamePrep()

  #
  # eGroups Prep - make sure eGroups directory is there
  #                and mount sony
  #
  egroupsPrep()

  #
  # Read the database into gDatabase
  #
  readDb()

  #
  # Look at our database entry
  #
  try:
    machine = gDatabase[host]
  except KeyError:
    appExit(1,  "\n\nExiting. Can't find host [%s] in the database" % host)

  print machine


  keys = gDatabase['PriorityList']
  for system in keys:
    sys.stdout.write('system: [%s]'  % system)
     
    if machine.has_key(system): 
       (status, tmp) = commands.getstatusoutput('/egroups/tmpSony/root/MachSetup/Setup%s.py %s' % (system, machine[system]) )
       if status != 0:
         appExit(1, "Exiting. Subsystem setup [Setup%s.py] failed\n...%s" % (system, tmp) )
       print ' Successful'

    
  r = os.system('/bin/umount /egroups/tmpSony')
  if r != 0:
    appExit(1, "Exiting. Subsystem setup [Setup%s.py] failed." % system)
  gMountedSony = 0

  #diskCopy(drive)

  #
  # Ok, now setup various things...
  #
  #diskHostSetup(drive,name,ip)

  #os.chdir("/root")

  # Attempt to mount the disk
  #x = os.system("umount /d1" )
  #if x == 0:
  #  print "Drive is unmounted"
  #  return 


  end = time.time()

  print "DONE Time:%5.2f" % ((end - start))


if __name__ == "__main__":
  main(sys.argv, sys.stdout, os.environ)
