#!/usr/bin/python

import os, sys, requests, json
from st2client.client import Client

st2_endpoints = {
    'action': 'http://localhost:9101',
    'reactor': 'http://localhost:9101',
    'datastore': 'http://localhost:9101'
}

try:
  client = Client(st2_endpoints)
  bot_host = client.keys.get_by_name('bot_host').value
  if not bot_host:
    raise Exception('Key error with bot_host.')
  bot_port = client.keys.get_by_name('bot_port').value
  if not bot_port:
    raise Exception('Key error with bot_port.')
  bot_endpoint = client.keys.get_by_name('bot_endpoint').value
  if not bot_endpoint:
    raise Exception('Key error with bot_endpoint.')
except Exception, e:
  print e
  sys.exit(2)

sys.argv.pop(0)

data = {}
payload = {}
payload['source']=sys.argv[0]
sys.argv.pop(0)
payload['name']=sys.argv[0]
sys.argv.pop(0)

args = ' '.join(map(str,sys.argv))

try:
  json.loads(args)
  payload['msg'] = args
except ValueError, e:
  payload['msg'] = json.dumps({'message': args})

url = 'http://' + bot_host + ':' + bot_port + bot_endpoint
headers = {'content-type': 'application/json'}

data['payload'] = payload
r = requests.post(url,data=json.dumps(data),headers=headers)

print r.text
