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

INSTALL_DIR="/usr/local/imvee-satellite"
PLIST="/Library/LaunchDaemons/com.imvee.satellite.plist"
PLIST_ALT="/Library/LaunchDaemons/com.imvee.satellit.plist"
ETC_ZSHRC="/etc/zshrc"
BACKUP_ETC_ZSHRC="/etc/zshrc.imvee.bak"
QUEUE_DIR_OLD="/usr/local/var/imvee-satellite"  # Legacy path
QUEUE_DIR="/var/lib/imvee-satellite"             # Current path (Enterprise)
LOG_DIR="/var/log/imvee-satellite"
ZSH_HOOK_LINE_A='source /usr/local/imvee-satellite/zsh_hook.sh'
ZSH_HOOK_LINE_B='source /usr/local/imvee-satellit/zsh_hook.sh'

echo "==================================="
echo "  IMVEE Satellite - Uninstaller"
echo "==================================="
echo ""

# Detect OS
OS_TYPE="$(uname -s)"
case "$OS_TYPE" in
  Darwin) OS="macos" ;;
  Linux)  OS="linux" ;;
  *)      echo "Unsupported OS: $OS_TYPE"; exit 1 ;;
esac

echo "[1/5] Stopping services..."

if [ "$OS" = "macos" ]; then
  # macOS LaunchDaemon
  if [ -f "$PLIST" ]; then
    sudo launchctl bootout system "$PLIST" 2>/dev/null || sudo launchctl unload -w "$PLIST" 2>/dev/null || true
    sudo rm -f "$PLIST"
    echo "  ✓ LaunchDaemon removed"
  fi
  if [ -f "$PLIST_ALT" ]; then
    sudo launchctl bootout system "$PLIST_ALT" 2>/dev/null || true
    sudo rm -f "$PLIST_ALT"
  fi
  sudo launchctl disable system/com.imvee.satellite 2>/dev/null || true
  sudo launchctl disable system/com.imvee.satellit 2>/dev/null || true
elif [ "$OS" = "linux" ]; then
  # Linux systemd
  if systemctl is-active --quiet imvee-satellite 2>/dev/null; then
    sudo systemctl stop imvee-satellite
    echo "  ✓ Service stopped"
  fi
  if systemctl is-enabled --quiet imvee-satellite 2>/dev/null; then
    sudo systemctl disable imvee-satellite
  fi
  sudo rm -f /etc/systemd/system/imvee-satellite.service
  sudo systemctl daemon-reload 2>/dev/null || true
  echo "  ✓ systemd service removed"
fi

echo "[2/5] Killing residual processes..."
sudo pkill -f '/usr/local/imvee-satellite/agent' 2>/dev/null || true
sudo pkill -f 'imvee.*satellite' 2>/dev/null || true
sleep 1
echo "  ✓ Processes terminated"

echo "[3/5] Removing installed files..."
sudo rm -rf "$INSTALL_DIR"
sudo rm -rf "$QUEUE_DIR"
sudo rm -rf "$QUEUE_DIR_OLD"  # Legacy path
sudo rm -rf "$LOG_DIR"
echo "  ✓ Files removed"

echo "[4/5] Removing shell hooks..."

if [ "$OS" = "macos" ]; then
  # macOS: Entferne zsh hook aus /etc/zshrc
  if [ -f "$ETC_ZSHRC" ]; then
    if grep -Fq "$ZSH_HOOK_LINE_A" "$ETC_ZSHRC" || grep -Fq "$ZSH_HOOK_LINE_B" "$ETC_ZSHRC"; then
      sudo /usr/bin/sed -i '' -e '/source \/usr\/local\/imvee-satellite\/zsh_hook\.sh/d' -e '/source \/usr\/local\/imvee-satellit\/zsh_hook\.sh/d' "$ETC_ZSHRC"
      echo "  ✓ Removed hook from /etc/zshrc"
    fi
  fi

  # Cleanup weitere Shell-Configs
  for f in /etc/zprofile /etc/profile; do
    if [ -f "$f" ]; then
      sudo /usr/bin/sed -i '' -e '/source \/usr\/local\/imvee-satellite\/zsh_hook\.sh/d' -e '/source \/usr\/local\/imvee-satellit\/zsh_hook\.sh/d' "$f" 2>/dev/null || true
    fi
  done

  # Backup entfernen
  if [ -f "$BACKUP_ETC_ZSHRC" ]; then
    sudo rm -f "$BACKUP_ETC_ZSHRC"
  fi
fi

echo "[5/5] Cleaning user data..."

if [ "$OS" = "macos" ]; then
  USER_HOME_BASE="/Users"
else
  USER_HOME_BASE="/home"
fi

for user_home in "$USER_HOME_BASE"/*; do
  [ -d "$user_home" ] || continue
  user_zshenv="$user_home/.zshenv"
  user_queue_dir="$user_home/.local/share/imvee-satellite"

  # Entferne IMVEE exports aus .zshenv
  if [ -f "$user_zshenv" ]; then
    if grep -q "IMVEE_QUEUE" "$user_zshenv" 2>/dev/null; then
      if [ "$OS" = "macos" ]; then
        /usr/bin/sed -i '' -e '/^# IMVEE Satellite/,/^export IMVEE_DOCKER_QUEUE/d' "$user_zshenv"
        /usr/bin/sed -i '' -e '/^$/N;/^\n# IMVEE/d' "$user_zshenv" 2>/dev/null || true
      else
        sed -i '/^# IMVEE Satellite/,/^export IMVEE_DOCKER_QUEUE/d' "$user_zshenv"
      fi
      echo "  ✓ Cleaned $(basename "$user_home")/.zshenv"
    fi
  fi

  # Entferne User-Queue-Verzeichnis
  if [ -d "$user_queue_dir" ]; then
    rm -rf "$user_queue_dir"
    echo "  ✓ Removed queue dir for $(basename "$user_home")"
  fi
done

echo ""
echo "==================================="
echo "  ✓ Uninstall complete!"
echo "==================================="
echo ""
echo "Removed:"
echo "  • Agent binary: $INSTALL_DIR"
echo "  • Queue directories: $QUEUE_DIR, $QUEUE_DIR_OLD"
echo "  • Log directory: $LOG_DIR"
if [ "$OS" = "macos" ]; then
  echo "  • LaunchDaemon: $PLIST"
  echo "  • Shell hooks: /etc/zshrc"
else
  echo "  • systemd service: /etc/systemd/system/imvee-satellite.service"
fi
echo ""
echo "The agent has been completely removed from this system."
echo "You can now perform a fresh installation without --force."
echo ""
echo "⚠️  Please reload your shell to apply changes:"
echo "    exec zsh    (or open a new terminal)"
