#!/bin/bash

check_and_install() {
    local util=$1
    if ! command -v "$util" &> /dev/null; then
        echo "Utility '$util' not found. Please install it."
        echo "-------------------------------------"
        echo "Debian/Ubuntu: sudo apt install $util"
        echo "Fedora/CentOS/RHEL: sudo dnf install $util"
        echo "Arch Linux: sudo pacman -S $util"
        echo "macOS (Homebrew): brew install $util"
        echo "-------------------------------------"
        exit 1
    fi
}

# Checking curl
check_and_install "curl"

# Checking jq
check_and_install "jq"

TEMPLATES_DIR=$1
ZABBIX_URL=$2/api_jsonrpc.php
AUTH_TOKEN=$3

if [ -z "$ZABBIX_URL" ] || [ -z "$AUTH_TOKEN" ] || [ -z "$TEMPLATES_DIR" ]; then
  echo "Usage: $0 <TEMPLATES_DIR> <ZABBIX_API_URL> <AUTH_TOKEN>"
  exit 1
fi

# --- Import YAML-files ---
# Search for YAML files in the directory
find "$TEMPLATES_DIR" -name "*.yaml" | sort | while read -r FILE; do
  echo "Importing file: ${FILE}..."

  JSON_OUTPUT=$(cat "$FILE" | jq -Rs '{"jsonrpc": "2.0", "method": "configuration.import", "params": {"format": "yaml", "source": ., "rules": {"hosts":{"createMissing":true,"updateExisting":true},"templates":{"createMissing":true,"updateExisting":true},"templateLinkage":{"createMissing":true,"deleteMissing":true},"discoveryRules":{"createMissing":true,"updateExisting":true,"deleteMissing":true},"items":{"createMissing":true,"updateExisting":true,"deleteMissing":true},"triggers":{"createMissing":true,"updateExisting":true,"deleteMissing":true},"graphs":{"createMissing":true,"updateExisting":true,"deleteMissing":true},"maps":{"createMissing":true,"updateExisting":true},"images":{"createMissing":true,"updateExisting":true},"valueMaps":{"createMissing":true,"updateExisting":true},"templateDashboards":{"createMissing":true,"updateExisting":true}}}, id: 1}')

  # Sending request to Zabbix API
  IMPORT_RESPONSE=$(echo "$JSON_OUTPUT" | curl -s -X POST \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $AUTH_TOKEN" \
    --data-binary @- \
    "$ZABBIX_URL"
  )

  # checking the response for success or error
  IMPORT_RESULT=$(echo "$IMPORT_RESPONSE" | jq -r '.result')
  IMPORT_ERROR=$(echo "$IMPORT_RESPONSE" | jq -r '.error.data')

  if [ "$IMPORT_RESULT" != "null" ]; then
    echo "Successfully imported ${FILE}."
  else
    echo "Import error ${FILE}: ${IMPORT_ERROR}"
  fi

  echo "---"
done

echo "All YAML files have been processed."