#!/bin/bash
set -euo pipefail

LOG_FILE="/var/log/polkit-removal.log"
PACKAGE="policykit-1"

echo "=== $(date) ===" | tee -a "$LOG_FILE"
echo "PolicyKit (polkit) Non-interactive Uninstall Script for Debian" | tee -a "$LOG_FILE"

# Check if installed
if ! dpkg -l | grep -q "^ii  $PACKAGE "; then
  echo "✅ $PACKAGE is not installed." | tee -a "$LOG_FILE"
  exit 0
fi

echo "🔍 Simulating removal..." | tee -a "$LOG_FILE"
SIM_OUTPUT=$(mktemp)
sudo apt-get -s remove --purge $PACKAGE > "$SIM_OUTPUT"

# Analyze simulation: look for "Remv" lines other than policykit-1
REMOVED_PKGS=$(awk '/Remv/ {print $2}' "$SIM_OUTPUT" | grep -v "^$PACKAGE$" || true)

if [[ -n "$REMOVED_PKGS" ]]; then
  echo "❌ Removal would also uninstall the following packages:" | tee -a "$LOG_FILE"
  echo "$REMOVED_PKGS" | tee -a "$LOG_FILE"
  echo "❗ Skipping actual removal. Manual intervention required." | tee -a "$LOG_FILE"
  rm -f "$SIM_OUTPUT"
  exit 1
fi

echo "✅ Only $PACKAGE will be removed. Proceeding with uninstallation." | tee -a "$LOG_FILE"

sudo apt-get remove --purge -y $PACKAGE | tee -a "$LOG_FILE"
sudo apt-get autoremove -y | tee -a "$LOG_FILE"

echo "🔄 Verifying removal..." | tee -a "$LOG_FILE"
if dpkg -l | grep -q "^ii  $PACKAGE "; then
  echo "❌ $PACKAGE is still installed!" | tee -a "$LOG_FILE"
else
  echo "✅ $PACKAGE has been removed." | tee -a "$LOG_FILE"
fi

if command -v polkitd >/dev/null 2>&1; then
  echo "❌ polkitd binary still present at: $(which polkitd)" | tee -a "$LOG_FILE"
else
  echo "✅ polkitd binary not found." | tee -a "$LOG_FILE"
fi

rm -f "$SIM_OUTPUT"