#!/usr/bin/env bash

MASON_COMMAND=$1 ; shift
MASON_NAME=$1 ; shift
MASON_VERSION=$1 ; shift

set -e
set -o pipefail

MASON_RELEASED_VERSION="0.1.0"

if [ "${MASON_COMMAND}" = "--version" ]; then
    echo ${MASON_RELEASED_VERSION}
    exit 0
fi

function usage {
    echo "Usage: $0 <command> <lib> <version>"
}

if [ -z "${MASON_COMMAND}" ]; then
    usage
    exit 1
fi

ROOTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" > /dev/null && pwd )"
MASON_DIR=${MASON_DIR:-$ROOTDIR}

if [ "${MASON_COMMAND}" = "env" ]; then
    . ${MASON_DIR}/mason.sh > /dev/null
    eval echo \$${MASON_NAME}
    exit
fi

if [ -z "${MASON_NAME}" ]; then
    usage
    echo "Missing <lib>"
    exit 1
elif [ -z "${MASON_VERSION}" ]; then
    usage
    echo "Missing <version>"
    exit 1
fi

if [ "${MASON_COMMAND}" = "trigger" ]; then
    if [ -z "${TRAVIS_TOKEN}" ]; then
        echo "TRAVIS_TOKEN is not set."
        exit 1
    fi

    config=$(ruby <<RUBY
    require 'yaml'
    require 'json'
    config = YAML.load_file("scripts/${MASON_NAME}/${MASON_VERSION}/.travis.yml")
    config["env"] ||= {}
    config["env"]["global"] ||= []
    config["env"]["global"] << "MASON_NAME=${MASON_NAME}" << "MASON_VERSION=${MASON_VERSION}"
    puts JSON.pretty_generate(config)
RUBY
    )

    body="{
      \"request\": {
        \"message\": \"Building ${MASON_NAME} ${MASON_VERSION}\",
        \"branch\": \"$(git rev-parse --abbrev-ref HEAD)\",
        \"config\": ${config}
      }
    }"

    curl -s -X POST https://api.travis-ci.org/repo/mapbox%2Fmason/requests \
        -H "Content-Type: application/json" \
        -H "Accept: application/json" \
        -H "Travis-API-Version: 3" \
        -H "Authorization: token ${TRAVIS_TOKEN}" \
        -d "$body"

    echo "Now go to https://travis-ci.org/mapbox/mason/builds to view build status"

    exit
fi

. ${MASON_DIR}/mason.sh

export MASON_DIR
bash "${MASON_DIR}/scripts/${MASON_NAME}/${MASON_VERSION}/script.sh" "${MASON_COMMAND}" "$@"
