#!/bin/sh

set -eu

if [ $# -lt 2 ]; then
  echo "usage: $0 TEAM PROJECT [BUILD] [ENVIRONMENT] [NJOBS]"
  exit 1
fi

TEAM="$1"
PROJECT="$2"
BUILD=${3:-}
ENVIRONMENT="${4:-testenv}"
NJOBS="${5:-1}"

checkdep() {
  if ! which "$1" > /dev/null; then
    echo "E: $1 not found; please install ${2:-$1}"
    exit 1
  fi
}

# dependencies
checkdep curl
checkdep parallel moreutils

./manage.py shell <<EOF
from squad.ci.models import Backend
Backend.objects.get_or_create(
    name="fake",
    url="https://www.example.com/",
    username='example',
    token='example',
    implementation_type='fake',
)
EOF

export AUTH_TOKEN=$(./manage.py get-token "$TEAM/$PROJECT")

parallel -i curl --fail "http://localhost:8000/api/submitjob/$TEAM/$PROJECT/$BUILD/$ENVIRONMENT" \
  --fail \
  --silent --output /dev/null \
  --header "Auth-Token: $AUTH_TOKEN" \
  --form backend=fake \
  --form definition="something, it does not matter" \
  -- $(seq 1 "$NJOBS")
