#!/bin/bash
set -eo pipefail

INPUT=/dev/stdin
if [ -t 0 ]; then
    if [ "$#" -ne 1 ]; then
        echo "ERROR: Illegal number of parameters."
        echo "INFO:  Use 'pipefail Jenkinsfile' or 'cat Jenkinsfile | pipefail'"
        exit 1
    fi
    INPUT=$1
fi
# put credentials inside ~/.netrc
# define JENKINS_URL in your user profile
JENKINS_URL=${JENKINS_URL:-http://localhost:8080}

# failure to get crumb is ignored as this may be diabled on the server side
CRUMB="-H `curl -nfs "$JENKINS_URL/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,%22:%22,//crumb)"`" || CRUMB=''

# The tee+grep trick assures that the exit code is 0 only if the server replied with "successfully validated"
curl -nfs -X POST $CRUMB -F "jenkinsfile=<-" $JENKINS_URL/pipeline-model-converter/validate <$INPUT \
  | tee >(cat 1>&2) | grep 'successfully validated' >/dev/null
