#!/usr/bin/env bash

set -o nounset -o errexit -o pipefail

# Check crumb
echo "Checking for CSRF..."
CRUMB=$(curl --fail -0 -u "{{ vars['jenkins_user'] }}:{{ vars['jenkins_password'] }}" ''{{ vars['jenkins_url'] }}'/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)' 2>/dev/null || echo "N/A")
if [[ ${CRUMB} != "N/A" ]]; then
  echo "CSRF Enabled."
else
  echo "CSRF not enabled."
fi

# Create node (doCreateItem)
RESPONSE=$(curl -L -s -o /dev/null -w "%{http_code}" -u "{{ vars['jenkins_user'] }}:{{ vars['jenkins_password'] }}" -H "Content-Type:application/x-www-form-urlencoded" -H "$CRUMB" -X POST -d 'json={"name": "'"{{ vars['node_name'] }}"'", "nodeDescription": "'"{{ vars['description']|default('node') }}"'", "numExecutors": "'"2"'", "remoteFS": "'"/home/jenkins"'", "labelString": "'"{{ vars['labels'] }}"'", "mode": "NORMAL", "": ["hudson.plugins.sshslaves.SSHLauncher", "hudson.slaves.RetentionStrategy$Always"], "launcher": {"stapler-class": "hudson.plugins.sshslaves.SSHLauncher", "$class": "hudson.plugins.sshslaves.SSHLauncher", "host": "'"{{ vars['node'] }}"'", "credentialsId": "'"{{ vars['credsid'] }}"'", "port": "'"22"'", "javaPath": "", "jvmOptions": "", "prefixStartSlaveCmd": "", "suffixStartSlaveCmd": "", "launchTimeoutSeconds": "", "maxNumRetries": "", "retryWaitTime": ""}, "retentionStrategy": {"stapler-class": "hudson.slaves.RetentionStrategy$Always", "$class": "hudson.slaves.RetentionStrategy$Always"}, "nodeProperties": {"stapler-class-bag": "true"}, "type": "hudson.slaves.DumbSlave", "crumb": "'"$CRUMB"'"}' "{{ vars['jenkins_url'] }}/computer/doCreateItem?name={{ vars['node_name'] }}&type=hudson.slaves.DumbSlave")


if [[ ${RESPONSE} == "200" ]]; then
  echo "Node Created: {{ vars['node_name'] }}"
else
  echo "ERROR: Failed to create node. Response code: [${RESPONSE}]"
  exit 1
fi
