#!/usr/bin/env bash
set -Eeuo pipefail
umask 077

API_URL="${NICE_ZABBIX_API_URL:-https://127.0.0.1/api_jsonrpc.php}"
SECRETS="/etc/nice-monitoring/secrets.env"
STATE="/var/lib/nice-monitoring/template-state"
UPSTREAM="/usr/share/zabbix/templates"
NICE="/usr/share/nice-monitoring/templates"

log() { printf '[nice-template-sync] %s\n' "$*"; }
die() { log "ERROR: $*"; exit 1; }

[[ -r "$SECRETS" ]] || die "Missing $SECRETS"
# shellcheck disable=SC1090
source "$SECRETS"
[[ -n "${ADMIN_PASSWORD:-}" ]] || die "ADMIN_PASSWORD missing"
mkdir -p "$STATE"

api() {
    local method="$1" params="$2" token="${3:-}"
    local -a h=(-H 'Content-Type: application/json-rpc')
    [[ -z "$token" ]] || h+=(-H "Authorization: Bearer $token")
    curl -ksS --fail-with-body "$API_URL" "${h[@]}" \
      --data "{\"jsonrpc\":\"2.0\",\"method\":\"$method\",\"params\":$params,\"id\":1}"
}

json_field() {
    local path="$1"
    php -r '
      $j=json_decode(stream_get_contents(STDIN),true);
      $v=$j;
      foreach(explode(".",$argv[1]) as $k) {
        if ($k==="") continue;
        if (!is_array($v) || !array_key_exists($k,$v)) exit(2);
        $v=$v[$k];
      }
      echo is_array($v) ? json_encode($v) : $v;
    ' "$path"
}

login="$(api user.login "{\"username\":\"Admin\",\"password\":\"${ADMIN_PASSWORD}\",\"userData\":true}")"
token="$(printf '%s' "$login" | json_field result.sessionid)" || die "API login failed"

rules='{
  "template_groups":{"createMissing":true,"updateExisting":true},
  "templates":{"createMissing":true,"updateExisting":true},
  "templateLinkage":{"createMissing":true,"deleteMissing":false},
  "items":{"createMissing":true,"updateExisting":true,"deleteMissing":false},
  "discoveryRules":{"createMissing":true,"updateExisting":true,"deleteMissing":false},
  "triggers":{"createMissing":true,"updateExisting":true,"deleteMissing":false},
  "graphs":{"createMissing":true,"updateExisting":true,"deleteMissing":false},
  "httptests":{"createMissing":true,"updateExisting":true,"deleteMissing":false},
  "valueMaps":{"createMissing":true,"updateExisting":true,"deleteMissing":false},
  "templateDashboards":{"createMissing":true,"updateExisting":true,"deleteMissing":false}
}'

import_one() {
    local file="$1"
    local source params response
    source="$(php -r 'echo json_encode(file_get_contents($argv[1]), JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);' "$file")"
    params="{\"format\":\"yaml\",\"rules\":${rules},\"source\":${source}}"
    if response="$(api configuration.import "$params" "$token" 2>&1)"; then
        if grep -q '"result":true' <<<"$response"; then
            return 0
        fi
    fi
    return 1
}

# Frozen upstream catalog: import once per exact catalog package release.
up_marker="$STATE/upstream-8.0.0rc1-63915eb0-0.6.done"
if [[ ! -f "$up_marker" ]]; then
    log "Importing frozen upstream Zabbix 8 template catalog"
    mapfile -t pending < <(find "$UPSTREAM" -type f \( -name '*.yaml' -o -name '*.yml' \) | sort)
    total="${#pending[@]}"
    pass=0
    while ((${#pending[@]} > 0 && pass < 8)); do
        ((pass+=1))
        next=()
        ok=0
        for f in "${pending[@]}"; do
            if import_one "$f"; then
                ((ok+=1))
            else
                next+=("$f")
            fi
        done
        log "upstream pass $pass: imported=$ok deferred=${#next[@]}"
        ((${#next[@]} < ${#pending[@]})) || break
        pending=("${next[@]}")
    done

    if ((${#pending[@]} > 0)); then
        printf '%s\n' "${pending[@]}" > "$STATE/upstream-import-failures.txt"
        log "WARNING: ${#pending[@]} upstream template files were not imported; list saved for review"
    fi
    printf 'catalog_total=%s\nremaining=%s\n' "$total" "${#pending[@]}" > "$up_marker"
fi

# NICE-owned templates are managed on every product upgrade.
log "Importing NICE managed templates"
while IFS= read -r -d '' f; do
    import_one "$f" || die "NICE template import failed: $f"
done < <(find "$NICE" -type f \( -name '*.yaml' -o -name '*.yml' \) -print0 | sort -z)

api user.logout '[]' "$token" >/dev/null 2>&1 || :
date -u +%FT%TZ > "$STATE/nice-0.1.4.done"
log "Template synchronization complete"
