#!/bin/sh
#
# UJS REST-v1 Beispiel mit curl.
#
# Test-Konfiguration:
# Diese Werte sind direkt eingetragen, damit das Script ohne weitere
# Umgebungsvariablen aufgerufen werden kann.
#
# Direkt aufrufen:
#   ./example.sh WHOAMI
#   ./example.sh POST test_payload.json
#   ./example.sh POST '{"type":"test_note","customer_no":"TEST-1001","data":{"title":"Hallo"}}'
#   ./example.sh LIST
#   ./example.sh GET 123
#   ./example.sh DELETE 123
#   ./example.sh TEST

UJS_BASE_URL="https://dev.jsonstorage.de"
UJS_MODULE="testmodul"
UJS_TOKEN="2618a9dd9eba3515b50c427d66e5635b1bda91cf443e51ce"
UJS_CUSTOMER_NO="TEST-1001"
UJS_DEFAULT_TYPE="test_note"

ujs_fail() {
  echo "Fehler: $1" >&2
  exit 1
}

ujs_urlencode() {
  if command -v python3 >/dev/null 2>&1; then
    python3 -c 'import sys, urllib.parse; print(urllib.parse.quote(sys.argv[1]))' "$1"
  elif command -v python >/dev/null 2>&1; then
    python -c 'import sys, urllib; print(urllib.quote(sys.argv[1]))' "$1"
  else
    printf '%s' "$1"
  fi
}

ujs_check_config() {
  [ -n "$UJS_BASE_URL" ] || ujs_fail "UJS_BASE_URL ist leer."
  [ -n "$UJS_MODULE" ] || ujs_fail "UJS_MODULE ist leer."
  [ -n "$UJS_TOKEN" ] || ujs_fail "UJS_TOKEN ist leer."
}

ujs_request() {
  method="$1"
  path="$2"
  body="${3:-}"

  ujs_check_config

  if [ -n "$body" ]; then
    curl -sS \
      -X "$method" \
      -H "Authorization: Bearer $UJS_TOKEN" \
      -H "Content-Type: application/json" \
      -H "X-Request-ID: example-$(date +%s)-$$" \
      --data "$body" \
      "$UJS_BASE_URL/api/v1$path"
  else
    curl -sS \
      -X "$method" \
      -H "Authorization: Bearer $UJS_TOKEN" \
      -H "X-Request-ID: example-$(date +%s)-$$" \
      "$UJS_BASE_URL/api/v1$path"
  fi
}

ujs_default_payload() {
  printf '%s\n' '{
  "type": "'"$UJS_DEFAULT_TYPE"'",
  "customer_no": "'"$UJS_CUSTOMER_NO"'",
  "data": {
    "title": "UJS Testeintrag",
    "status": "open",
    "created_by": "example.sh",
    "amount": 129.90
  },
  "tags": ["testmodul", "shell"]
}'
}

ujs_payload_from_arg() {
  payload_arg="${1:-}"

  if [ -z "$payload_arg" ]; then
    ujs_default_payload
    return
  fi

  if [ -f "$payload_arg" ]; then
    cat "$payload_arg"
    return
  fi

  printf '%s' "$payload_arg"
}

ujs_whoami() {
  ujs_request "GET" "/whoami"
}

ujs_post_entry() {
  body="$(ujs_payload_from_arg "${1:-}")"
  ujs_request "POST" "/modules/$(ujs_urlencode "$UJS_MODULE")/entries" "$body"
}

ujs_list_entries() {
  ujs_request "GET" "/modules/$(ujs_urlencode "$UJS_MODULE")/entries?customer_no=$(ujs_urlencode "$UJS_CUSTOMER_NO")&limit=10"
}

ujs_get_entry() {
  [ -n "$1" ] || ujs_fail "GET braucht eine ID."
  ujs_request "GET" "/modules/$(ujs_urlencode "$UJS_MODULE")/entries/$1"
}

ujs_delete_entry() {
  [ -n "$1" ] || ujs_fail "DELETE braucht eine ID."
  ujs_request "DELETE" "/modules/$(ujs_urlencode "$UJS_MODULE")/entries/$1"
}

ujs_json_entry_id() {
  if command -v python3 >/dev/null 2>&1; then
    python3 -c 'import json,sys; data=json.load(sys.stdin); print(data.get("entry", {}).get("id", ""))'
  elif command -v python >/dev/null 2>&1; then
    python -c 'import json,sys; data=json.load(sys.stdin); print(data.get("entry", {}).get("id", ""))'
  else
    sed -n 's/.*"id"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' | head -n 1
  fi
}

ujs_test() {
  echo "=== WHOAMI ==="
  ujs_whoami
  echo

  echo "=== POST Demo-Eintrag ==="
  created="$(ujs_post_entry)"
  echo "$created"
  echo

  id="$(printf '%s' "$created" | ujs_json_entry_id)"
  if [ -n "$id" ]; then
    echo "=== GET $id ==="
    ujs_get_entry "$id"
    echo

    echo "=== LIST ==="
    ujs_list_entries
    echo

    if [ "$UJS_DELETE_AFTER" = "1" ]; then
      echo "=== DELETE $id ==="
      ujs_delete_entry "$id"
      echo
    fi
  fi
}

ujs_usage() {
  cat <<'EOF'
UJS example.sh

Aufrufe:
  ./example.sh WHOAMI
  ./example.sh POST
  ./example.sh POST payload.json
  ./example.sh POST '{"type":"test_note","customer_no":"TEST-1001","data":{"title":"Hallo"}}'
  ./example.sh LIST
  ./example.sh GET <id>
  ./example.sh DELETE <id>
  ./example.sh TEST

Vorher oben in der Datei setzen:
  UJS_BASE_URL
  UJS_MODULE
  UJS_TOKEN
EOF
}

if [ "$(basename "$0")" = "example.sh" ]; then
  command_name="$(printf '%s' "${1:-TEST}" | tr '[:lower:]' '[:upper:]')"

  case "$command_name" in
    WHOAMI) ujs_whoami ;;
    POST) ujs_post_entry "${2:-}" ;;
    LIST) ujs_list_entries ;;
    GET) ujs_get_entry "${2:-}" ;;
    DELETE) ujs_delete_entry "${2:-}" ;;
    TEST) ujs_test ;;
    HELP|-H|--HELP) ujs_usage ;;
    *) ujs_usage; exit 1 ;;
  esac
fi
