#!/usr/bin/env/ruby
require 'socket'

### CONSTANTES ###
  CURRENT_DIR = File.dirname(__FILE__)
  # AWS API Credentials
    AWS_ACCESS_KEY_ID     = "<put_your_access_key_here>" #Account AWS #7
    AWS_SECRET_ACCESS_KEY = "<put_your_secret_key_here>"
  # Knife config
    KNIFE_CONF_FILE       = "#{CURRENT_DIR}/knife.rb"
  # AWS Instance config and sizing
    REGION                = "eu-west-1"
class String
 def red()
    "\e[31m#{self}\e[0m"
 end
end
 # Define the command to purge the instance
  list_instances_cmd = [
    "knife ec2 server list",
    "--config #{KNIFE_CONF_FILE}",
    "--aws-access-key-id #{AWS_ACCESS_KEY_ID}",
    "--aws-secret-access-key #{AWS_SECRET_ACCESS_KEY}",
    "--region #{REGION}",
    " | grep -E 'running|pending' | grep ecp | cut -d ' ' -f1"
  ].join(" ")
puts "-- Debut du script de purge".red
@instances =  `#{list_instances_cmd}`.split()
if @instances.nil? or @instiances == ""
  puts "-- Aucune instance EC2 a purger".red
else
  @instances.each do |instance|
    puts " -- Suppression de l'instance : #{instance}".red
    # Define the command to purge the instance
    purge_cmd = [
      "knife ec2 server delete #{instance}",
      "--config #{KNIFE_CONF_FILE}",
      "--aws-access-key-id #{AWS_ACCESS_KEY_ID}",
      "--aws-secret-access-key #{AWS_SECRET_ACCESS_KEY}",
      "--region #{REGION}",
      "--verbose",
      "--yes"
    ].join(" ")
    system(purge_cmd)
  end
end
puts "-- Fin du script de purge".red
