#!/usr/bin/env ruby

require 'rubygems'
require 'getopt/std'
require 'yaml'
require 'zabbixapi'

opt = Getopt::Std.getopts("g:E:")

group_name = opt["g"]
zabbix_env = opt["E"]

template_name = "TMPL_Availability"

# read config
config = YAML::load(open('./config.yml'))

api_url = config[zabbix_env]["api_url"]
api_login = config[zabbix_env]["api_login"]
api_password = config[zabbix_env]["api_password"]


# Esablish new connection
zbx = Zabbix::ZabbixApi.new(api_url, api_login, api_password)

# Create new template
p " * Creating template #{template_name}."
g_id = zbx.add_or_get_group(group_name)

options = {
  'groups' => [ g_id.to_i ],
  'host' => template_name
}

t_id = zbx.add_or_get_template(options)

# Create application #{app_name}
app_name = "Availability"
p " ** Create application #{app_name}."
application = {
  'hostid' => t_id,
  'name' => app_name
}
a_id = zbx.add_or_get_application(t_id, application)

# 'Ping.'
options = {
  'description' => "Ping",
  'key_' => "agent.ping",
  'hostid' => t_id.to_i,
  'applications' => [ a_id.to_i ],
  'history' => 7,
  'trends' => 30,
  'delay' => 30,
  'value_type' => 0,
  'type' => '0'
}
p " ** Add 'Ping' to #{template_name}."
i_id = zbx.add_or_get_item(t_id, options)

# TRIGGERS
options = {
  'description' => "Host availability",
  'expression' => "{#{template_name}:agent.ping.nodata(61)}=1",
  'priority' => 5, #disaster
  'templateid' => 0,
  'comments' => "Host availability",
  'type' => 0,
  'status' => '0'
}

p " ** Add 'Host availability disaster trigger'"
tr_id = zbx.add_or_get_trigger(t_id, options)