#!/bin/bash
set -o pipefail

ITOP_URL="https://itop-dev.allarddcs.nl"
ITOP_USER="tekton"
ITOP_PWD="Itop01@@@"
ORGANIZATION="0001"
TITLE="Containerchange"
DESCRIPTION="Container created"
CALLER="0001"
COMMENT="new version of container olproperties has been pushed"
CHANGE="RoutineChange"

JSON_DATA=$(jq -c <<EOF
{
  "operation": "core/create",
  "class": "${CHANGE}",
  "fields": {
    "org_id": "${ORGANIZATION}",
    "title": "${TITLE}",
    "description": "${DESCRIPTION}"
  },
  "caller": "${CALLER}",
  "comment": "${COMMENT}"
}
EOF
)

echo "=== DEBUG: JSON payload (compact) ==="
echo "$JSON_DATA"
echo "====================================="

POST_DATA=$(printf \
  'auth_user=%s&auth_pwd=%s&json_data=%s' \
  "$ITOP_USER" \
  "$ITOP_PWD" \
  "$(printf '%s' "$JSON_DATA" | jq -sRr @uri)"
)

echo "=== DEBUG: POST data (URL-encoded) ==="
echo "$POST_DATA"
echo "====================================="

echo "=== DEBUG: Sending request to iTop ==="

HTTP_RESPONSE=$(wget \
  --timeout=15 \
  --tries=1 \
  --server-response \
  --no-check-certificate \
  --header="Content-Type: application/x-www-form-urlencoded" \
  --post-data="$POST_DATA" \
  -O - \
  "${ITOP_URL}/webservices/rest.php?version=1.0" 2>&1)

WGET_RC=$?

echo "=== DEBUG: wget exit code ==="
echo "$WGET_RC"

echo "=== DEBUG: Raw response ==="
echo "$HTTP_RESPONSE"
echo "==========================="

JSON_BODY=$(echo "$HTTP_RESPONSE" | sed -n '/^{/,$p')

if [[ -z "$JSON_BODY" ]]; then
  echo "ERROR: No JSON returned from iTop"
  exit 1
fi

echo "=== DEBUG: Parsed JSON ==="
echo "$JSON_BODY" | jq .
echo "=========================="

CODE=$(echo "$JSON_BODY" | jq -r '.code // -1')
MESSAGE=$(echo "$JSON_BODY" | jq -r '.message // empty')

if [[ "$CODE" == "0" ]]; then
  KEY=$(echo "$JSON_BODY" | jq -r '.objects[].key')
  echo "SUCCESS: Change created, key=$KEY"
  exit 0
else
  echo "ERROR: iTop rejected the request"
  echo "Code   : $CODE"
  echo "Message: $MESSAGE"
  exit 1
fi
