#!/usr/bin/ruby

require 'fileutils'
require 'open-uri'
require 'json'
require 'emr/common'

class Installer

  # bucketName is a token that will be replaced by the s3 artifact deployer by the actual bucket name where this file is uploaded
  BUCKET_NAME = "elasticmapreduce"

  GANGLIA_HADOOP_VERSION_MAP = 
  {
    "default" => "1.0",
    "0.18" => "1.0",
    "0.20" => "1.0",
    "0.20.205" => "2.0",
    "1.0.3" => "2.0"
  }


  def install_ganglia
    jobflow_info = Emr::JsonInfoFile.new("job-flow")
    hadoop_version = jobflow_info['hadoopVersion']
    logger = Emr::Logger.new
    executor = Emr::Executor.new(logger)
    
    if hadoop_version != nil && GANGLIA_HADOOP_VERSION_MAP.has_key?(hadoop_version) then
      version_num = GANGLIA_HADOOP_VERSION_MAP[hadoop_version]
    else
      version_num = GANGLIA_HADOOP_VERSION_MAP["default"]
    end
    
    executor.run("rm -f ganglia-installer")
    
    if `cat /etc/*-release 2>/dev/null | grep 'Amazon'` == ""
      # http://http.us.debian.org/debian has been removed, and http://http.us.debian.org/debian-lts doesn't have all needed packages
      executor.run("sudo cp /etc/apt/sources.list /etc/apt/sources.list.old");
      executor.run("sed -e 's%http://http.us.debian.org/debian *squeeze%http://archive.debian.org/debian squeeze%' /etc/apt/sources.list.old | sudo tee /etc/apt/sources.list > /dev/null");
      executor.run("sudo apt-get install -y debian-keyring debian-archive-keyring");
      executor.run("sudo apt-get clean");
      executor.run("sudo apt-get update");
      executor.run("hadoop fs -copyToLocal s3://#{BUCKET_NAME}/bootstrap-actions/ganglia/#{version_num}/ganglia-installer .")
    else
      executor.run("hadoop fs -copyToLocal s3://#{BUCKET_NAME}/bootstrap-actions/ganglia/amz/ganglia-installer .")
    end
          
    executor.run("chmod +x ganglia-installer")
    executor.run("sudo ./ganglia-installer")
  end
end

LOCAL_GANGLIA_INSTALLER = "/usr/share/aws/emr/scripts/install-ganglia"
logger = Emr::Logger.new
retriesLeft = 5
if File.exist?(LOCAL_GANGLIA_INSTALLER) then
  logger.log "Found script on AMI itself, going to run: #{LOCAL_GANGLIA_INSTALLER}"
  executor = Emr::Executor.new(logger)
  executor.run("sudo chmod +x #{LOCAL_GANGLIA_INSTALLER}")
  executor.run("sudo #{LOCAL_GANGLIA_INSTALLER}")
else
  begin
    Installer.new.install_ganglia
  rescue Exception => e
    logger.log "Failed to install ganglia: #{e.to_s}"
    retriesLeft = retriesLeft - 1
    if retriesLeft > 0
      logger.log "Retrying with #{retriesLeft} attemps remaining"
      retry
    end
    logger.log "Failed to install ganglia"
    raise
  end
end
