#!/bin/bash

### deb-control ###
# Section: utils
#
# Depends: bash, sudo
# Description:'
#  Command availability checker and installer helper.
#   Usage:
#    checkcmd <command> [package|.] [mode]
#   Verifies whether a command is present in PATH. If it is missing,
#   it can optionally try to resolve an apt package by command name or by
#   using apt-file when available, and then install it with sudo apt-get.
#   .
#   The optional mode allows prompting before installation, and the helper
#   can be used in scripts to ensure required commands are available.
#   .
#  '
###/deb-control

print_usage() {
    cat <<'EOF'
Usage:
  checkcmd <command> [package|.] [mode]
EOF
}

print_help() {
    print_usage
    cat <<'EOF'

Modes:
  (empty) - default (show messages)
  0       - silent mode (no success message if already installed)
  1       - optional mode (ask before installing)

Special value for package:
  "."     - auto detect package using apt-file if available,
            otherwise fallback to the command name
EOF
}

set -euo pipefail

SOURCE="${4:-}"

case "${1:-}" in
    -h|--help)
        print_help
        exit 0
        ;;
esac

CMD="${1:-}"
PKG="${2:-}"
MODE="${3:-}"
SOURCE="${4:-}"

if [[ -z "$CMD" ]]; then
    print_usage >&2
    echo "Call --help for more information." >&2
    exit 1
fi

# ====================== CHECK IF ALREADY INSTALLED ======================
if command -v "$CMD" >/dev/null 2>&1; then
    if [[ -z "$MODE" ]]; then
        echo "✓ Command '$CMD' is already installed."
    fi
    exit 0
fi

echo "➤ Command '$CMD' not found."

# ====================== OPTIONAL MODE (1) — ASK USER ======================
if [[ "$MODE" == "1" && "$SOURCE" != "apt-file" ]]; then
    if [[ "$PKG" == "." || -z "$PKG" ]]; then
        echo "Command '$CMD' is missing. Try to find and install package? [Y/n]"
    else
        echo "Package '$PKG' is required for '$CMD'. Install it? [Y/n]"
    fi
    if [[ "$PKG" == "." ]]; then
        PKG="$CMD"
    fi
    read -r choice
    if [[ "$choice" =~ ^[Nn]$ ]]; then
        echo "⏭️  Skipping installation. Continuing without '$CMD'."
        exit 0
    fi
fi

# ====================== DETERMINE PACKAGE ======================
if [[ -z "$PKG" || "$PKG" == "." ]]; then
    if [[ "$SOURCE" != "apt-file" ]]; then
        echo " 🔍 Trying to find suitable package for '$CMD'..."
        if command -v apt-file >/dev/null 2>&1; then
            PKG=$(apt-file search --regexp "/(usr/|)(bin|sbin)/${CMD}$" 2>/dev/null | head -n1 | cut -d':' -f1)
            if [[ -n "$PKG" ]]; then
                echo " Found package: $PKG"
                exec "$0" "$CMD" "$PKG" "" "apt-file"
            fi
        fi

        echo " apt-file not available or no match found. Using package name '$CMD'."
        PKG="$CMD"
    fi
else
    echo " Will install package: $PKG"
fi

# ====================== INSTALLATION ======================
echo " Updating package list..."
sudo apt-get update -qq

echo " Installing $PKG..."
if sudo apt-get install -y "$PKG"; then
    if command -v "$CMD" >/dev/null 2>&1; then
        echo "✅ Success! Command '$CMD' is now available (from package '$PKG')."
        exit 0
    else
        echo "⚠️ Package '$PKG' installed, but command '$CMD' still not found." >&2
        exit 1
    fi
else
    echo "❌ Failed to install package '$PKG'." >&2
    echo " Check sudo rights and internet connection." >&2
    exit 1
fi
