#!/bin/bash
set -euo pipefail

# 📁 Paths
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_FILE="${SCRIPT_DIR}/arr_healthcheck.conf"
EXCEPTIONS_FILE="${SCRIPT_DIR}/arr_healthcheck_exceptions.conf"
TMP_EXCEPTIONS="${SCRIPT_DIR}/arr_healthcheck_exceptions.tmp"
REPO_DIR="/opt/scripts_remote"
TARGET_FILE="monitoring/arr_healthcheck_exceptions.conf"

declare -A FOUND_SOURCES=()
declare -A EXISTING_DESCRIPTIONS=()

# 🔍 Check required tools
if ! command -v jq >/dev/null || ! command -v curl >/dev/null; then
  echo "❌ 'jq' and 'curl' are required."
  exit 2
fi

# 📄 Check config file
if [[ ! -f "$CONFIG_FILE" ]]; then
  echo "❌ Config file '$CONFIG_FILE' not found."
  exit 2
fi

echo "🔎 Extracting 'source' fields from configured apps..."

# 🔁 1. Read all sources from healthcheck APIs
while IFS="|" read -r name url api_path api_key _ || [[ -n "$name" ]]; do
  [[ -z "$name" || "$name" =~ ^# ]] && continue

  full_url="${url}${api_path}"
  echo "→ Fetching from $name..."

  response=$(curl -fsS -H "X-Api-Key: $api_key" "$full_url" || echo "")
  [[ -z "$response" ]] && echo "  ⚠️  No response, skipping." && continue

  for src in $(echo "$response" | jq -r '.[].source' 2>/dev/null); do
    FOUND_SOURCES["$src"]=1
  done
done < "$CONFIG_FILE"

# 📄 2. Load existing descriptions (if file exists)
if [[ -f "$EXCEPTIONS_FILE" ]]; then
  while IFS="|" read -r source description || [[ -n "$source" ]]; do
    [[ -z "$source" || "$source" =~ ^# ]] && continue
    EXISTING_DESCRIPTIONS["$source"]="$description"
  done < "$EXCEPTIONS_FILE"
fi

# 🧬 3. Merge and write final list
{
  echo "# source|description"
  for source in "${!FOUND_SOURCES[@]}"; do
    desc="${EXISTING_DESCRIPTIONS[$source]:-}"
    echo "$source|$desc"
  done | sort
} > "$TMP_EXCEPTIONS"

mv "$TMP_EXCEPTIONS" "$EXCEPTIONS_FILE"
echo "✅ Merged and updated: $EXCEPTIONS_FILE"

# 💾 4. Git commit & push as user dbi
if sudo -u dbi git -C "$REPO_DIR" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  if ! sudo -u dbi git -C "$REPO_DIR" diff --quiet -- "$TARGET_FILE"; then
    echo "🔧 Committing changes to Git as user dbi..."
    sudo -u dbi git -C "$REPO_DIR" add "$TARGET_FILE"
    sudo -u dbi git -C "$REPO_DIR" commit -m "Update arr_healthcheck_exceptions.conf from healthcheck source extraction"
    sudo -u dbi git -C "$REPO_DIR" push
    echo "🚀 Changes pushed to remote repository."
  else
    echo "ℹ️  No changes to commit."
  fi
else
  echo "⚠️  '$REPO_DIR' is not a Git repository. Skipping Git operations."
fi