#!/usr/bin/env bash
set -euo pipefail

SRC_DIR="/usr/share/cmk-push-agent/plugins"
AGENT_DIR="/usr/lib/check_mk_agent/plugins"

log()  { printf '[%s] %s\n' "$(date -Is)" "$*" >&2; }
warn() { log "WARN: $*"; }
die()  { log "ERROR: $*"; exit 2; }

[[ -d "$SRC_DIR" ]]   || die "Source dir not found: $SRC_DIR"
[[ -d "$AGENT_DIR" ]] || die "Agent plugins dir not found: $AGENT_DIR"

is_candidate() {
  local f="$1"
  [[ -f "$f" && -r "$f" ]] || return 1
  case "$(basename -- "$f")" in
    .*|*~|*.bak|*.disabled) return 1 ;;
  esac
  return 0
}

run_detect() {
  local plugin_file="$1"

  # Detect must be executed via --detect and only exit code matters.
  # Stdout/stderr are suppressed (but you can remove redirections for debugging).
  "$plugin_file" --detect >/dev/null 2>&1
}

ensure_enabled() {
  local plugin_file="$1"
  local name linkpath

  name="$(basename -- "$plugin_file")"
  linkpath="$AGENT_DIR/$name"

  # If link exists, ensure it points to our managed source.
  if [[ -L "$linkpath" ]]; then
    local current
    current="$(readlink -- "$linkpath" || true)"
    if [[ "$current" != "$plugin_file" ]]; then
      rm -f -- "$linkpath"
      ln -s -- "$plugin_file" "$linkpath"
      log "ENABLED (updated link): $name"
    else
      log "ENABLED (already): $name"
    fi
    return 0
  fi

  # If a regular file exists there, do not overwrite.
  if [[ -e "$linkpath" && ! -L "$linkpath" ]]; then
    warn "Cannot enable $name: $linkpath exists and is not a symlink"
    return 0
  fi

  ln -s -- "$plugin_file" "$linkpath"
  log "ENABLED: $name"
}

ensure_disabled() {
  local plugin_file="$1"
  local name linkpath

  name="$(basename -- "$plugin_file")"
  linkpath="$AGENT_DIR/$name"

  if [[ -L "$linkpath" ]]; then
    local current
    current="$(readlink -- "$linkpath" || true)"
    # Safety: remove only if it points into our SRC_DIR
    if [[ "$current" == "$SRC_DIR/"* ]]; then
      rm -f -- "$linkpath"
      log "DISABLED: $name"
    else
      warn "Not removing $name: symlink points outside managed dir ($current)"
    fi
  else
    log "DISABLED (already): $name"
  fi
}

# Deterministic iteration
mapfile -d '' plugins < <(find "$SRC_DIR" -maxdepth 1 -type f -print0 | sort -z)

if [[ ${#plugins[@]} -eq 0 ]]; then
  log "No plugin files found in $SRC_DIR"
  exit 0
fi

for f in "${plugins[@]}"; do
  is_candidate "$f" || continue

  # Require executable, otherwise detect/agent execution won't work.
  if [[ ! -x "$f" ]]; then
    warn "Skipping $(basename -- "$f"): not executable (chmod 0755)"
    continue
  fi

  if run_detect "$f"; then
    ensure_enabled "$f"
  else
    rc=$?
    if [[ "$rc" -eq 1 ]]; then
      ensure_disabled "$f"
    else
      warn "detect returned $rc for $(basename -- "$f") -> disabling for safety"
      ensure_disabled "$f"
    fi
  fi
done
