#!/bin/bash
set -euo pipefail

# ---- SUDO CHECK ----
check_sudo() {
  if sudo -n true 2>/dev/null; then
    echo "✅ User '$USER' has sudo rights."
  else
    echo "❌ User '$USER' does not have passwordless sudo rights."
    echo "   Please ensure you can run 'sudo apt-get ...' without a password."
    exit 1
  fi
}
check_sudo

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TOOLS_FILE="$SCRIPT_DIR/tools.txt"

if [[ ! -f "$TOOLS_FILE" ]]; then
  echo "❌ Tools list file '$TOOLS_FILE' not found."
  exit 1
fi

echo "🔄 Updating apt package lists..."
sudo apt-get update -y

while read -r TOOL; do
  [[ -z "$TOOL" || "$TOOL" =~ ^# ]] && continue

  echo "🔍 Checking if package '$TOOL' is installed..."
  PKG_OK=false
  CMD_OK=false

  if dpkg -s "$TOOL" &> /dev/null; then
    PKG_OK=true
  fi

  # If the package is a binary, check if it's in PATH
  if command -v "$TOOL" &>/dev/null; then
    CMD_OK=true
  fi

  if [[ "$PKG_OK" = true && "$CMD_OK" = true ]]; then
    echo "✅ $TOOL is already installed."
  else
    echo "➕ Installing $TOOL..."
    sudo apt-get install -y "$TOOL" || { echo "❌ Failed to install $TOOL!"; exit 1; }
    if command -v "$TOOL" &>/dev/null; then
      echo "✅ $TOOL installed and available in PATH."
    else
      echo "❌ $TOOL is not in PATH after installation."
      exit 1
    fi
  fi
done < "$TOOLS_FILE"

echo "🎉 All requested tools are installed and available in PATH."