#!/bin/sh
# Easy to use trigger-script for cron and docker automated builds
# Just place your config in e.g. ./trigger.d/*.conf

# check if needed files are provided
if [ $# -lt 2 ]; then
  echo "No enough arguments provided."
  echo "Usage: $0 <repo> <tag|'all'> "
  exit 1
fi

# load configuration file
path="$( cd "$(dirname "$0")" ; pwd -P )"
if [ -f "$1" ]; then
  source "$1"
elif [ -f "${path}/trigger.d/$1.conf" ]; then
  source "${path}/trigger.d/$1.conf"
else
  echo "Could not find configuration file."
  exit 1
fi

# check variables
if [ -z "$REPO" ] || [ -z "$TOKEN" ] || [ -z "$TAGS" ]; then
  echo "Not all configuration vairables given"
  exit 1
fi

# Script
ARGS=()
arg_found=false
triggers=0

if [ "$2" == all ]; then
  echo "Trigger all..."
  curl -sH "Content-Type: application/json" --data '{"build": true}' -X POST https://cloud.docker.com/api/build/v1/source/${REPO}/trigger/${TOKEN}/call/
  arg_found=true
  triggers=$((triggers+1))
else
  for arg in "${@:2}"
  do
  echo "arg: ${arg}"
    for tag in "${TAGS[@]}"
    do
        if [ "$tag" == "$arg" ]; then
            ARGS+=("$tag")
            arg_found=true
            break
        fi
    done

    if [ "$arg_found" != true ] ; then
        echo $"Tag '$arg' not found."
        arg_found=false
    fi
  done

  if [ ${#ARGS[@]} -eq 0 ] && [ $triggers -eq 0 ] ; then
    echo $"No Tags are given or not found."
    printf "Usage: $0 {"
    printf '%s|' "${TAGS[@]}"
    printf  "}\n"
    exit 1
  fi

  for tag in "${ARGS[@]}"
  do
    if [ $triggers -lt 1 ] ; then
      echo "Trigger '$tag'."
      curl -sH "Content-Type: application/json" --data '{"docker_tag": "'${tag}'"}' -X POST https://cloud.docker.com/api/build/v1/source/${REPO}/trigger/${TOKEN}/call/
      triggers=$((triggers+1))
    else
      echo "Ignoring '$tag'."
    fi
  done
fi
