#
#   Miscellaneous functions related to the Controller, launchpads, server slots, generator slots, etc.
#

class ControllerMisc

  #
  # Set up global variables.
  #
  # Prerequisite  environment variables:
  #       TTC_CONFIG, something like /tooltwist/tooltwist_X_Z/devel/ttc/config
  #       TTC_DEPLOY, something like /ControllerV8
  #
  def self.setupGlobals(launchpad_name)
    $LAUNCHPAD_NAME = launchpad_name
    
    #
    # Get environment variables
    #
    
    # TTC_CONFIG, something like ${TTC_HOME}/devel/ttc/config
    $TTC_CONFIG = ENV['TTC_CONFIG']
    if $TTC_CONFIG == nil or  $TTC_CONFIG == ""
      softbomb "Environment variable TTC_CONFIG is not defined"
    end
    if not File.directory?($TTC_CONFIG)
      softbomb "Environment variable TTC_CONFIG refers to an invalid directory: #{$TTC_CONFIG}"
    end
       
    # TTC_DEPLOY, something like /ControllerV8
    $TTC_DEPLOY = ENV['TTC_DEPLOY']
    if $TTC_DEPLOY == nil or  $TTC_DEPLOY == ""
      bomb "Environment variable TTC_DEPLOY is not defined"
    end
    if not File.directory?($TTC_DEPLOY)
      bomb "Environment variable TTC_DEPLOY refers to an invalid directory: #{$TTC_DEPLOY}"
    end
  
    $TTC_HOST = ENV['TTC_HOST']
    $TTC_PORT = ENV['TTC_PORT']
    $GENCONF_HOME = ENV['GENCONF_HOME']
    $CUSTCONF_HOME = ENV['CUSTCONF_HOME']
    $JENKINS_HOME = ENV['JENKINS_HOME']
    $JENKINS_PORT = ENV['JENKINS_PORT']
    $OS = ENV['OS']
    $JAVAC_MEMORY = ENV['JAVAC_MEMORY']
    $JAVAC_DEBUG = ENV['JAVAC_DEBUG']
    
    $THIS_SCRIPT = File.basename(__FILE__)
    $BIN_DIR = File.expand_path(File.dirname(__FILE__))
    
    #
    # Set other values
    #
    $CONTROLLER_HOME = "/ControllerV8"
    $LAUNCHPAD_HOME = "#{$TTC_DEPLOY}/launchpads"         #ZZZZZ Is this really used anywhere?
    $LAUNCHPAD_DIR = "#{$TTC_DEPLOY}/launchpads/#{launchpad_name}"
    $IMAGE_DIR = "#{$TTC_DEPLOY}/launchpads/#{launchpad_name}/image"
    $BUILD_FILE = "#{$LAUNCHPAD_DIR}/build.xml"
    $SUMMARY_FILE = "#{$LAUNCHPAD_DIR}/CONFIG_SUMMARY"
  end


  #
  # Load the launchpad configuration
  #
  def self.loadLaunchpadDetails(launchpad_name)
    #print "\nloadLaunchpadDetails(#{launchpad_name})\n"

    launchpadFile = "#{$TTC_DEPLOY}/config-files/launchpad.#{launchpad_name}.xml"
    launchpadDef = XmlSimple.xml_in(launchpadFile)
    #description = launchpadDef['description'].to_s
    $LAUNCHPAD_TYPE = launchpadDef['type'].to_s
    #latestStatus = launchpadDef['latestStatus'].to_s
    #disable = launchpadDef['disable'].to_s
    return launchpadDef
  end

  #
  #   Load the generator slot configuration into global variables
  #
  def self.loadGeneratorSlotDetails(launchpad_name)
    #print "\nloadGeneratorSlotDetails(#{launchpad_name})\n"
    
    $GENERATOR_SLOT_NAME = 'ZZZ$GENERATOR_SLOT_NAME'
    $GENERATOR_DESCRIPTION = 'ZZZ$GENERATOR_DESCRIPTION'
    $GENERATOR_HTTP_PORT = 'ZZZ$GENERATOR_HTTP_PORT'
    $GENERATOR_HTTPS_PORT = 'ZZZ$GENERATOR_HTTPS_PORT'
    $GENERATOR_SERVER_PORT = 'ZZZ$GENERATOR_SERVER_PORT'
    $GENERATOR_AJP_PORT = 'ZZZ$GENERATOR_AJP_PORT'
    $GENERATOR_DISABLE = 'ZZZ$GENERATOR_DISABLE'
    $GENERATOR_INSTALL_TOMCAT = 'ZZZ$GENERATOR_INSTALL_TOMCAT'
    $GENERATOR_IMAGEMAGICK_HOME = 'ZZZ$GENERATOR_IMAGEMAGICK_HOME'
    return true
    
    # generatorDef = nil
    # Dir["#{$TTC_DEPLOY}/config-files/generatorSlot.*.xml"].each do | file |
    #   xml = XmlSimple.xml_in(file)
    #   lp = xml['launchpadUsingThisSlot'].to_s
    #   if lp == launchpad_name
    #     regex = /generatorSlot\.(\S+)\.xml/
    #     $GENERATOR_SLOT_NAME = regex.match(file)[1] # match $1
    #     generatorDef = xml
    #     $GENERATOR_DESCRIPTION = xmlValue(file, xml, 'description', true)
    #     $GENERATOR_HTTP_PORT = xmlValue(file, xml, 'httpPort')
    #     $GENERATOR_HTTPS_PORT = xmlValue(file, xml, 'httpsPort')
    #     $GENERATOR_SERVER_PORT = xmlValue(file, xml, 'serverPort')
    #     $GENERATOR_AJP_PORT = xmlValue(file, xml, 'ajpPort')
    #     $GENERATOR_DISABLE = xmlValue(file, xml, 'disable', true)   #ZZZZZZZZZZ Check this
    #     $GENERATOR_INSTALL_TOMCAT = xmlValue(file, xml, 'installTomcat', true)
    #     $GENERATOR_IMAGEMAGICK_HOME = xmlValue(file, xml, 'imagemagickHome')
    #     return true
    #     break
    #   end
    # end
    # return false # generator slot not found
  end

  #
  #   Load the server slot configuration into global variables
  #
  def self.loadServerSlotDetails(launchpad_name)
    #print "\nloadServerSlotDetails(#{launchpad_name})\n"
    
    # Find a server mapped onto this launchpad -> server_xml
    server_xml = nil
    server_file = nil
    required_group = nil
    Dir["#{$TTC_DEPLOY}/config-files/serverSlot.*.xml"].each do | file |
      xml = XmlSimple.xml_in(file)
      lp = xml['launchpadUsingThisSlot'][0].to_s
      if lp == launchpad_name
        
        # This server is mapped onto the launchpad. Use it's XML definition
        regex = /serverSlot\.(\S+)\.xml/
        $PRODUCTION_SLOT_NAME = regex.match(file)[1] # match $1
        is_group = xmlValue(file, xml, 'isGroup')
        if is_group == "Y"
          required_group = $PRODUCTION_SLOT_NAME
        end
        server_xml = xml
        server_file = file
        break
      end
    end
    
    if (server_xml == nil)
      # No server for this launchpad
      return false
    end

    # Is this a group?
    if required_group != nil
print "Launchpad #{launchpad_name} uses group #{required_group}\n"
      
      # This is a group, so find the first server in the group -> server_xml
      server_xml = nil
      Dir["#{$TTC_DEPLOY}/config-files/serverSlot.*.xml"].each do | file |
        xml = XmlSimple.xml_in(file)
        group = xml['group'].to_s
        if group == required_group
          
          # This is the correct group. Use it's XML defintion
          regex = /serverSlot\.(\S+)\.xml/
          $PRODUCTION_SLOT_NAME = regex.match(file)[1] # match $1
print "Server #{$PRODUCTION_SLOT_NAME} is the first in the group.\n"
          server_xml = xml
          server_file = file
          break
        end
      end
      
      # Check that the group had a server
      if (server_xml == nil)
        # No server for this launchpad
        return false
      end
    end
    
    # Get details from the server's XML
print "Using config from server #{$PRODUCTION_SLOT_NAME} for all servers in this group.\n"
print "server_file = #{server_file}\n"
    $PRODUCTION_DESCRIPTION = xmlValue(server_file, server_xml, 'description', true)
    $PRODUCTION_IS_GROUP = xmlValue(server_file, server_xml, 'isGroup')
    $PRODUCTION_SERVER_HOME = xmlValue(server_file, server_xml, 'serverHome')
    $PRODUCTION_WEBAPP_NAME = xmlValue(server_file, server_xml, 'webappName')
    $PRODUCTION_HTTP_PORT = xmlValue(server_file, server_xml, 'httpPort')
    $PRODUCTION_HTTPS_PORT = xmlValue(server_file, server_xml, 'httpsPort')
    $PRODUCTION_SERVER_PORT = xmlValue(server_file, server_xml, 'serverPort')
    $PRODUCTION_AJP_PORT = xmlValue(server_file, server_xml, 'ajpPort')
    $PRODUCTION_WEBAPPS_DIR = xmlValue(server_file, server_xml, 'webappsDir')
    $PRODUCTION_TOMCAT_HOME = xmlValue(server_file, server_xml, 'tomcatHome')
    $PRODUCTION_INSTALL_CMD = xmlValue(server_file, server_xml, 'installCmd')
    $PRODUCTION_INSTALL_METHOD = xmlValue(server_file, server_xml, 'installMethod')
    $PRODUCTION_SERVER = xmlValue(server_file, server_xml, 'server')
    $PRODUCTION_USERNAME = xmlValue(server_file, server_xml, 'username')
    $PRODUCTION_PASSWORD = xmlValue(server_file, server_xml, 'password')
    $PRODUCTION_INSTALL_TOMCAT = xmlValue(server_file, server_xml, 'installTomcat')
    $PRODUCTION_IMAGEMAGICK_HOME = xmlValue(server_file, server_xml, 'imagemagickHome')
    $PRODUCTION_SSH_PORT = xmlValue(server_file, server_xml, 'sshPort')
    $PRODUCTION_FIP_PORT = xmlValue(server_file, server_xml, 'fipPort')
    return true
  end
  
  def  self.deploymentConfigFile(launchpad_name)
    config_file = "#{$TTC_DEPLOY}/config-files/deploymentConfig.#{launchpad_name}.xml"
    return config_file
  end
  
  #
  # Load the payload details
  #
  def self.loadPayloadDetails(launchpad_name)
    print "loadPayloadDetails(#{launchpad_name})\n"
    config_file = self.deploymentConfigFile(launchpad_name)
    print "Config file is #{config_file}\n"
    if not File.exist?(config_file); bomb("Unknown file #{config_file}\n") end
    deploymentConfig = XmlSimple.xml_in(config_file)
    return deploymentConfig
  end
  
  #
  # Return the path to the generator filter definition
  #
  def self.filterConfigFile(launchpad_name)
    filterConfig = "#{$TTC_DEPLOY}/config-files/filters.#{launchpad_name}.xml"
    return filterConfig
  end
  
end # ControllerMisc end


#
# A terrible error has occurred - bomb out, removing the summary and build.xml files
#
def bomb(msg)
  # Display the error message
  print "\n**\n** Fatal error: #{msg}\n**\n\n"
  # Remove the build and summary file.
  if $BUILD_FILE != nil and File.exist?($BUILD_FILE)
    print "- removing #{$BUILD_FILE}.\n"
    FileUtils.rm($BUILD_FILE)
  end
  if $SUMMARY_FILE != nil and File.exist?($SUMMARY_FILE)
    print "- removing #{$SUMMARY_FILE}.\n"
    FileUtils.rm($SUMMARY_FILE)
  end
  # Display the error message and exit with an error status
  STDOUT.flush
  exit!(false)
end

#
# A fatal error has occurred - bomb out, but unlink 'bomb' don't delete summary and build.xml
#
def softbomb(msg)
  # Display the error message and exit with an error status
  print "\n**\n** Fatal error: #{msg}\n**\n\n"
  STDOUT.flush
  exit!(true)
end
