#!/usr/bin/env python
# Copyright (C) 2012 Zulip, Inc.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import sys
import os


# Configure this script as a Tddium post-build task and it will send
# messages to Zulip when a build finishes.
#
# Expects Tddium environment variables plus:
#
#   ZULIP_USER    e.g. builds@solanolabs.com
#   ZULIP_API_KEY e.g. 00000000000000000000000000000000
#   ZULIP_STREAM  e.g. builds
#
# If ZULIP_API_KEY is not specified, it will be read from
# ~/.zulip-api-key.


# Path to the directory where zulip.py lives.
# Here we assume it's in the parent of the directory
# where this script lives.

zulip_directory = os.path.join(os.path.dirname(__file__), '../api')


sys.path.append(zulip_directory)
import zulip

client = zulip.Client(
    client  = "ZulipTddiumNotifier/0.1",
    email   = os.environ['ZULIP_USER'],
    api_key = os.environ.get('ZULIP_API_KEY'))

tddium_server = os.environ.get('TDDIUM_API_SERVER', 'api.tddium.com')
report_url    = 'https://%s/1/reports/%s' % (tddium_server, os.environ['TDDIUM_SESSION_ID'])
repo_name     = os.path.basename(os.environ['TDDIUM_REPO_ROOT'])

result = client.send_message(dict(
    type    = 'stream',
    to      = os.environ['ZULIP_STREAM'],
    subject = 'build for ' + repo_name,
    content = '%s [%s](%s)' %
        (repo_name, os.environ['TDDIUM_BUILD_STATUS'], report_url)))

if result['result'] != 'success':
    sys.stderr.write('Error sending to Zulip:\n%s\n' % (result['msg'],))
    sys.exit(1)