#!/usr/bin/env ruby
######################################################
###
##  File: hipchat_cli.rb
##  Desc: send a message to a hipchat room using v2 API from the command line
#
# Example Using the Hipchat gem

if ARGV.empty?  || ARGV.first.start_with?('-')
  puts <<~EOS

    Example of how to send a message to a hipchat room.  uses
    the system environment variables:
      HIPCHAT_ROOM    # the intended room for the message to be delivered
      HIPCHAT_TOKEN   # the API token for the hipchat.com account
      HIPCHAT_SERVER  # The customer server domain; defaults to the standard hipchat server
      HIPCHAT_USER    # Name to be displayed as the sender. Must be <= 20 characters

    Whatever you put on the command line will be sent as the message.

  EOS
  exit
end

message = ARGV.join(' ')

hc_room   = ENV['HIPCHAT_ROOM']
hc_server = ENV['HIPCHAT_SERVER']
hc_token  = ENV['HIPCHAT_TOKEN']

unless hc_room && hc_token
  puts <<~EOS

    The following system environment variables are required:

      HIPCHAT_ROOM .... current value: #{ENV['HIPCHAT_ROOM']}
      HIPCHAT_TOKEN ... current value: #{ENV['HIPCHAT_TOKEN']}

    The following system environment variables are optional:

      HIPCHAT_SERVER .. current value: #{ENV['HIPCHAT_SERVER']}
      HIPCHAT_USER .... current value: #{ENV['HIPCHAT_USER']}

  EOS
  exit
end


require 'hipchat'


name_of_sender    = ENV['HIPCHAT_USER'] || 'Hipchat CLI Program' # must be less than 20 chacters

if name_of_sender.size > 20
  name_of_sender = name_of_sender[0,20]
  puts <<~EOS

    WARNING: The HIPCHAT_USER value exceeded 20 characters limit - it was truncated.
             Value was: '#{ENV['HIPCHAT_USER']}'
             Value is:  '#{name_of_sender}'

  EOS
end


if hc_server.nil? || hc_server.empty?
  client = HipChat::Client.new(api_token, :api_version => 'v2') # use the default server
else
  client = HipChat::Client.new(hc_token, :api_version => 'v2', :server_url => "https://#{hc_server}")
end


client[hc_room].send(name_of_sender, message, notify: true, color: 'green')
