#!/bin/bash

set -e

MARKER_DIR="/etc/setup-markers"
MARKER="$MARKER_DIR/netdata_postfix_disabled"

# Ensure user has sudo rights
if ! sudo -v &> /dev/null; then
  echo "❌ This script requires sudo privileges."
  exit 1
fi

# Check if already configured
if [ -f "$MARKER" ]; then
  echo "✅ Marker found: postfix plugin already disabled. Skipping."
  exit 0
fi

# Check Netdata config directory
if [ ! -d /etc/netdata ]; then
  echo "❌ Netdata config directory /etc/netdata not found — is Netdata installed?"
  exit 2
fi

# Check if /etc/netdata is a symlink to /opt/netdata
resolved_path=$(readlink -f /etc/netdata)
if [[ "$resolved_path" == /opt/netdata* ]]; then
  echo "⚠️ Detected that /etc/netdata is a symlink to /opt/netdata."
  echo "This is a non-standard setup. Manual review is recommended."
  exit 3
fi

# Write override config
echo "🔧 Writing override config to disable postfix plugin..."

cat <<EOF | sudo tee /etc/netdata/go.d.override.yaml > /dev/null
# netdata postfix plugin disabled
postfix:
  enabled: no
EOF

# Restart Netdata if active
if systemctl is-active --quiet netdata; then
  sudo systemctl restart netdata
  echo "🔄 Netdata service restarted."
else
  echo "ℹ️ Netdata service not active — not restarted."
fi

# Create marker file
echo "📝 Creating marker file at $MARKER"
sudo mkdir -p "$MARKER_DIR"
sudo touch "$MARKER"

echo "✅ Postfix plugin disabled and marker set."