#!/usr/bin/bash
# ==============================================================================
# flux-vprint: Main CLI Management & Control Tool
# Complete Fingerprint Reader Manager for ThinkPad T480 on openSUSE Tumbleweed
# ==============================================================================

set -e

# Version
FLUX_VERSION="1.0.0"

# Styling
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'

# Resolve base directory (where flux-vprint is located)
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do
  DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
done
SCRIPT_DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
PROJECT_ROOT="$( cd -P "$SCRIPT_DIR/.." >/dev/null 2>&1 && pwd )"

# Helper: check root
require_root() {
    if [[ $EUID -ne 0 ]]; then
        echo -e "${RED}[ERROR]${NC} This command requires administrator (root) privileges."
        echo -e "Please run with: ${BOLD}sudo flux-vprint $1${NC}"
        exit 1
    fi
}

# Subcommand: print banner
show_banner() {
    echo -e "${CYAN}${BOLD}"
    echo "  __ _            __     __           _       _   "
    echo " / _| |_   ___  __\\ \\   / /          (_)     | |  "
    echo "| |_| | | | \\ \\/ / \\ \\ / /____  _ __  _ _ __ | |_ "
    echo "|  _| | |_| |>  <   \\ V / '_  \\| '__|| | '_ \\| __|"
    echo "| | | |\\__,_/_/\\_\\   \\_/| |_) || |   | | | | | |_ "
    echo "|_| |_|                 | .__/ |_|   |_|_| |_|\\__|"
    echo "                        |_|                       "
    echo -e "${NC}ThinkPad T480 Fingerprint Reader Suite (v${FLUX_VERSION})${NC}"
    echo "openSUSE Tumbleweed • KDE Plasma Integration"
    echo "--------------------------------------------------------"
}

# Subcommand: status
cmd_status() {
    show_banner
    echo -e "${BOLD}System & Fingerprint Reader Health Check:${NC}\n"

    # 1. Hardware Detection
    echo -ne "  [1/5] Hardware Sensor (USB): "
    if lsusb -d 06cb:009a >/dev/null 2>&1; then
        DEV_INFO=$(lsusb -d 06cb:009a | sed -e 's/^[ \t]*//')
        echo -e "${GREEN}${BOLD}DETECTED${NC} (${DEV_INFO})"
    elif lsusb | grep -i -E "validity|synaptics" >/dev/null 2>&1; then
        DEV_INFO=$(lsusb | grep -i -E "validity|synaptics" | head -n 1)
        echo -e "${GREEN}${BOLD}DETECTED${NC} (${DEV_INFO})"
    else
        echo -e "${RED}${BOLD}NOT FOUND${NC} (Check BIOS if fingerprint reader is disabled)"
    fi

    # 2. Firmware Status
    echo -ne "  [2/5] Proprietary Firmware:  "
    FW_FILE="/usr/share/python-validity/6_07f_lenovo_mis_qm.xpfwext"
    RUN_FW="/run/python-validity/6_07f_lenovo_mis_qm.xpfwext"
    if [[ -f "${FW_FILE}" ]]; then
        echo -e "${GREEN}${BOLD}INSTALLED${NC} (${FW_FILE})"
        if [[ -f "${RUN_FW}" || -L "${RUN_FW}" ]]; then
            echo -e "        Active Runtime Link:   ${GREEN}OK${NC} (${RUN_FW})"
        else
            echo -e "        Active Runtime Link:   ${YELLOW}MISSING${NC} (Will link on service start)"
        fi
    else
        echo -e "${YELLOW}${BOLD}MISSING${NC} (Run 'sudo flux-vprint fetch-fw')"
    fi

    # 3. Systemd Services
    echo -ne "  [3/5] Validity Driver Service: "
    if systemctl is-active python3-validity.service >/dev/null 2>&1; then
        echo -e "${GREEN}${BOLD}ACTIVE (Running)${NC}"
    else
        echo -e "${RED}${BOLD}INACTIVE${NC} (python3-validity.service)"
    fi

    echo -ne "        Open-Fprintd D-Bus:      "
    if systemctl is-active open-fprintd.service >/dev/null 2>&1; then
        echo -e "${GREEN}${BOLD}ACTIVE (Running)${NC}"
    else
        echo -e "${RED}${BOLD}INACTIVE${NC} (open-fprintd.service)"
    fi

    echo -ne "        Resume / Sleep Hook:     "
    if systemctl is-enabled open-fprintd-resume.service >/dev/null 2>&1 || systemctl is-enabled python3-validity-suspend-hotfix.service >/dev/null 2>&1; then
        echo -e "${GREEN}${BOLD}ENABLED${NC}"
    else
        echo -e "${YELLOW}${BOLD}DISABLED${NC}"
    fi

    # 4. openSUSE PAM Status
    echo -ne "  [4/5] openSUSE PAM Auth:       "
    # flux-vprint patch: `pam-config -q --fp` produces no parseable output on
    # this openSUSE Tumbleweed version, so it can never match the grep below
    # even when PAM is correctly configured. Check the real PAM stack file
    # directly instead, which is the actual source of truth.
    if grep -qs "pam_fprintd.so" /etc/pam.d/common-auth-pc 2>/dev/null; then
        echo -e "${GREEN}${BOLD}ENABLED${NC} (Fingerprint login & sudo active)"
    else
        echo -e "${YELLOW}${BOLD}DISABLED${NC} (Run 'sudo flux-vprint setup-pam')"
    fi

    # 5. Enrolled Fingerprints
    echo -ne "  [5/5] Enrolled Fingers (${USER}): "
    if command -v fprintd-list >/dev/null 2>&1; then
        ENROLLED=$(fprintd-list "${USER}" 2>&1 || true)
        if echo "${ENROLLED}" | grep -q "found 1 devices"; then
            FINGERS=$(echo "${ENROLLED}" | grep -E "^ - #" || true)
            if [[ -n "${FINGERS}" ]]; then
                echo -e "${GREEN}${BOLD}ENROLLED${NC}"
                echo "${FINGERS}" | sed 's/^/        /'
            else
                echo -e "${YELLOW}${BOLD}NO FINGERS ENROLLED YET${NC}"
                echo -e "        Tip: Run ${BOLD}flux-vprint enroll${NC} or open ${BOLD}KDE System Settings -> Users${NC}"
            fi
        else
            echo -e "${YELLOW}Sensor not responding to query yet (service starting or needs reset)${NC}"
        fi
    else
        echo -e "${YELLOW}fprintd-clients not installed yet${NC}"
    fi

    echo "--------------------------------------------------------"
}

# Subcommand: install
cmd_install() {
    require_root "install"
    show_banner
    echo -e "${BLUE}${BOLD}[*] Starting flux-vprint automated installation for openSUSE...${NC}\n"

    # Detect active python3 minor version (e.g. 313)
    PY_VER_SHORT=$(python3 -c "import sys; print(f'{sys.version_info.major}{sys.version_info.minor}')")

    echo -e "${BLUE}[1/7] Installing required system packages via zypper...${NC}"
    PACKAGES=(
        "innoextract"
        "fprintd"
        "fprintd-pam"
        "python${PY_VER_SHORT}-pyusb"
        "python${PY_VER_SHORT}-cryptography"
        "python3-dbus-python"
        "python3-gobject"
        "glib2-devel"
    )

    # Filter available packages
    zypper --non-interactive --quiet in "${PACKAGES[@]}" || {
        echo -e "${YELLOW}[!] Some version-specific packages might have different names. Retrying generic names...${NC}"
        zypper --non-interactive in innoextract fprintd fprintd-pam python3-pyusb python3-cryptography python3-dbus-python python3-gobject
    }

    echo -e "${BLUE}[2/7] Disabling conflicting stock fprintd service...${NC}"
    systemctl stop fprintd.service 2>/dev/null || true
    systemctl disable fprintd.service 2>/dev/null || true
    systemctl mask fprintd.service 2>/dev/null || true

    echo -e "${BLUE}[3/7] Installing open-fprintd and python-validity driver components...${NC}"
    if [[ -d "${PROJECT_ROOT}/core/open-fprintd" ]]; then
        (cd "${PROJECT_ROOT}/core/open-fprintd" && python3 setup.py install --prefix=/usr --root=/ >/dev/null)
        rm -rf "${PROJECT_ROOT}/core/open-fprintd/build" "${PROJECT_ROOT}/core/open-fprintd/dist" "${PROJECT_ROOT}/core/open-fprintd/"*.egg-info
    fi
    if [[ -d "${PROJECT_ROOT}/core/python-validity" ]]; then
        (cd "${PROJECT_ROOT}/core/python-validity" && python3 setup.py install --prefix=/usr --root=/ >/dev/null)
        rm -rf "${PROJECT_ROOT}/core/python-validity/build" "${PROJECT_ROOT}/core/python-validity/dist" "${PROJECT_ROOT}/core/python-validity/"*.egg-info
        # flux-vprint patch: python-validity's setup.py installs dbus-service
        # via data_files, not scripts=[...]. setuptools' data_files install
        # strips executable permissions regardless of the source file's
        # mode, so systemd fails with "Permission denied" at EXEC every
        # time this is (re)installed. Re-assert it here rather than patching
        # upstream's setup.py.
        chmod +x /usr/lib/python-validity/dbus-service
    fi

    echo -e "${BLUE}[4/7] Deploying configuration, D-Bus policies, and udev rules...${NC}"
    mkdir -p /etc/python-validity
    mkdir -p /usr/lib/udev/rules.d
    mkdir -p /usr/lib/systemd/system
    mkdir -p /usr/lib/tmpfiles.d
    mkdir -p /usr/share/dbus-1/system.d

    cp -f "${PROJECT_ROOT}/config/dbus-service.yaml" /etc/python-validity/
    cp -f "${PROJECT_ROOT}/config/60-flux-vprint.rules" /usr/lib/udev/rules.d/
    cp -f "${PROJECT_ROOT}/config/flux-vprint-tmpfiles.conf" /usr/lib/tmpfiles.d/
    cp -f "${PROJECT_ROOT}/config/net.reactivated.Fprint.conf" /usr/share/dbus-1/system.d/
    cp -f "${PROJECT_ROOT}/config/io.github.uunicorn.Fprint.conf" /usr/share/dbus-1/system.d/

    # Also install flux-vprint binary globally if run from source dir
    if [[ ! -f /usr/bin/flux-vprint || "${SCRIPT_DIR}/flux-vprint" != "/usr/bin/flux-vprint" ]]; then
        cp -f "${SCRIPT_DIR}/flux-vprint" /usr/bin/flux-vprint
        chmod +x /usr/bin/flux-vprint
    fi

    echo -e "${BLUE}[5/7] Deploying systemd services...${NC}"
    cp -f "${PROJECT_ROOT}/systemd/python3-validity.service" /usr/lib/systemd/system/
    cp -f "${PROJECT_ROOT}/systemd/open-fprintd.service" /usr/lib/systemd/system/
    cp -f "${PROJECT_ROOT}/systemd/open-fprintd-resume.service" /usr/lib/systemd/system/
    cp -f "${PROJECT_ROOT}/systemd/python3-validity-suspend-hotfix.service" /usr/lib/systemd/system/

    echo -e "${BLUE}[6/7] Downloading and extracting sensor firmware...${NC}"
    bash "${PROJECT_ROOT}/firmware/fetch-firmware.sh" "/usr/share/python-validity"

    echo -e "${BLUE}[7/7] Configuring openSUSE PAM and activating services...${NC}"
    # flux-vprint patch: --fp maps to the legacy, no-longer-installed
    # pam_fp.so module on modern openSUSE Tumbleweed. --fprintd is the
    # correct flag, mapping to the actually-installed pam_fprintd.so.
    /usr/sbin/pam-config -a --fprintd

    systemd-tmpfiles --create /usr/lib/tmpfiles.d/flux-vprint-tmpfiles.conf 2>/dev/null || true
    udevadm control --reload-rules
    udevadm trigger
    systemctl daemon-reload

    systemctl enable --now open-fprintd.service
    systemctl enable --now python3-validity.service
    systemctl enable --now open-fprintd-resume.service
    systemctl enable --now python3-validity-suspend-hotfix.service

    echo -e "\n${GREEN}${BOLD}✓ flux-vprint has been successfully installed and activated!${NC}"
    echo -e "You can now enroll your fingerprint by running:"
    echo -e "  ${BOLD}flux-vprint enroll${NC}"
    echo -e "Or simply open ${BOLD}KDE System Settings -> Users -> Fingerprint${NC}."
}

# Subcommand: fetch-fw
cmd_fetch_fw() {
    require_root "fetch-fw"
    bash "${PROJECT_ROOT}/firmware/fetch-firmware.sh" "/usr/share/python-validity"
}

# Subcommand: enroll
cmd_enroll() {
    show_banner
    echo -e "${BOLD}Enrolling Fingerprint for user: ${CYAN}${USER}${NC}\n"
    if ! command -v fprintd-enroll >/dev/null 2>&1; then
        echo -e "${RED}[ERROR]${NC} 'fprintd-enroll' is not installed. Please run: ${BOLD}sudo flux-vprint install${NC}"
        exit 1
    fi

    echo "Select finger to enroll:"
    echo "  1) Right Index Finger (default)"
    echo "  2) Right Thumb"
    echo "  3) Right Middle Finger"
    echo "  4) Left Index Finger"
    echo "  5) Other"
    read -r -p "Enter choice [1-5, default: 1]: " CHOICE

    FINGER="right-index-finger"
    case "$CHOICE" in
        2) FINGER="right-thumb" ;;
        3) FINGER="right-middle-finger" ;;
        4) FINGER="left-index-finger" ;;
        5)
            read -r -p "Enter finger name (e.g. left-thumb): " CUSTOM_FINGER
            [[ -n "$CUSTOM_FINGER" ]] && FINGER="$CUSTOM_FINGER"
            ;;
        *) FINGER="right-index-finger" ;;
    esac

    echo -e "\n${BLUE}[*] Preparing sensor for ${BOLD}${FINGER}${NC}..."
    echo -e "${YELLOW}INSTRUCTIONS:${NC}"
    echo -e "  • Touch or swipe the sensor repeatedly when prompted."
    echo -e "  • Hold your finger steady for ~1 second on each touch."
    echo -e "  • Continue until enrollment is confirmed.\n"

    fprintd-enroll -f "${FINGER}" "${USER}"
    echo -e "\n${GREEN}${BOLD}Enrollment process finished.${NC}"
    echo -e "You can test recognition anytime with: ${BOLD}flux-vprint test${NC}"
}

# Subcommand: test / verify
cmd_test() {
    show_banner
    echo -e "${BOLD}Testing Fingerprint Verification for user: ${CYAN}${USER}${NC}\n"
    if ! command -v fprintd-verify >/dev/null 2>&1; then
        echo -e "${RED}[ERROR]${NC} 'fprintd-verify' is not installed."
        exit 1
    fi

    echo -e "${BLUE}[*] Swipe or touch your finger to test...${NC}"
    fprintd-verify "${USER}"
}

# Subcommand: reset (Factory Reset / re-pair sensor)
cmd_reset() {
    require_root "reset"
    show_banner
    echo -e "${YELLOW}${BOLD}[!] Factory Reset / Sensor Re-pairing${NC}"
    echo "This command clears stored hardware pairing keys in the fingerprint sensor."
    echo "Useful if the sensor was previously used in Windows or fails with protocol errors."
    read -r -p "Are you sure you want to reset the sensor? [y/N]: " CONFIRM
    if [[ "$CONFIRM" != [yY] && "$CONFIRM" != [yY][eE][sS] ]]; then
        echo "Reset aborted."
        exit 0
    fi

    echo -e "${BLUE}[*] Stopping services...${NC}"
    systemctl stop open-fprintd.service python3-validity.service 2>/dev/null || true

    RESET_SCRIPT=""
    if [[ -f "/usr/share/python-validity/playground/factory-reset.py" ]]; then
        RESET_SCRIPT="/usr/share/python-validity/playground/factory-reset.py"
    elif [[ -f "${PROJECT_ROOT}/core/python-validity/scripts/factory-reset.py" ]]; then
        RESET_SCRIPT="${PROJECT_ROOT}/core/python-validity/scripts/factory-reset.py"
    fi

    if [[ -n "$RESET_SCRIPT" ]]; then
        echo -e "${BLUE}[*] Executing sensor factory reset...${NC}"
        python3 "$RESET_SCRIPT" || {
            echo -e "${YELLOW}[!] Script encountered a non-zero exit; this may be normal if already uninitialized.${NC}"
        }
    else
        echo -e "${RED}[ERROR]${NC} Could not locate factory-reset.py"
    fi

    echo -e "${BLUE}[*] Restarting services...${NC}"
    systemctl restart open-fprintd.service python3-validity.service
    echo -e "${GREEN}${BOLD}✓ Sensor reset completed.${NC}"
}

# Subcommand: setup-pam
cmd_setup_pam() {
    require_root "setup-pam"
    echo -e "${BLUE}[*] Enabling fingerprint authentication in openSUSE PAM...${NC}"
    # flux-vprint patch: --fp maps to the legacy, no-longer-installed
    # pam_fp.so module on modern openSUSE Tumbleweed. --fprintd is the
    # correct flag, mapping to the actually-installed pam_fprintd.so.
    /usr/sbin/pam-config -a --fprintd
    echo -e "${GREEN}[+] Fingerprint PAM module enabled.${NC}"
}

# Subcommand: uninstall
cmd_uninstall() {
    require_root "uninstall"
    show_banner
    echo -e "${YELLOW}${BOLD}[!] Uninstalling flux-vprint...${NC}"
    read -r -p "Are you sure you want to uninstall flux-vprint? [y/N]: " CONFIRM
    if [[ "$CONFIRM" != [yY] && "$CONFIRM" != [yY][eE][sS] ]]; then
        echo "Uninstall aborted."
        exit 0
    fi

    echo -e "${BLUE}[*] Disabling PAM fingerprint auth...${NC}"
    # flux-vprint patch: --fp maps to the legacy, no-longer-installed
    # pam_fp.so module on modern openSUSE Tumbleweed. --fprintd is the
    # correct flag, mapping to the actually-installed pam_fprintd.so.
    /usr/sbin/pam-config -d --fprintd 2>/dev/null || true

    echo -e "${BLUE}[*] Stopping and disabling services...${NC}"
    systemctl disable --now open-fprintd.service python3-validity.service open-fprintd-resume.service python3-validity-suspend-hotfix.service 2>/dev/null || true
    systemctl unmask fprintd.service 2>/dev/null || true

    echo -e "${BLUE}[*] Removing service files, udev rules, and configs...${NC}"
    rm -f /usr/lib/systemd/system/python3-validity.service
    rm -f /usr/lib/systemd/system/open-fprintd.service
    rm -f /usr/lib/systemd/system/open-fprintd-resume.service
    rm -f /usr/lib/systemd/system/python3-validity-suspend-hotfix.service
    rm -f /usr/lib/udev/rules.d/60-flux-vprint.rules
    rm -f /usr/lib/tmpfiles.d/flux-vprint-tmpfiles.conf
    rm -f /usr/share/dbus-1/system.d/net.reactivated.Fprint.conf
    rm -f /usr/share/dbus-1/system.d/io.github.uunicorn.Fprint.conf
    rm -rf /usr/lib/flux-vprint
    rm -rf /usr/lib/python-validity
    rm -rf /usr/lib/open-fprintd
    rm -rf /usr/share/python-validity
    rm -rf /etc/python-validity
    rm -rf /var/cache/flux-vprint
    rm -rf /run/python-validity
    # flux-vprint patch: open-fprintd's setup.py installs a D-Bus
    # service-activation descriptor separately from the executable it
    # points at. Without removing it too, dbus-daemon will still try to
    # auto-activate net.reactivated.Fprint after uninstall by launching a
    # binary that no longer exists, which can hang or fail session-startup
    # sequences (observed specifically breaking KDE Plasma Wayland login,
    # while X11 tolerated it silently).
    rm -f /usr/share/dbus-1/system-services/net.reactivated.Fprint.service
    rm -f /usr/bin/flux-vprint

    systemctl daemon-reload
    udevadm control --reload-rules

    echo -e "${GREEN}${BOLD}✓ flux-vprint uninstalled cleanly.${NC}"
}

# Subcommand: help
cmd_help() {
    show_banner
    echo "Usage: flux-vprint <command>"
    echo ""
    echo "Commands:"
    echo "  status       Check status of hardware, firmware, services, and PAM"
    echo "  install      Perform complete automated setup and service activation (requires sudo)"
    echo "  enroll       Interactively enroll a fingerprint for the current user"
    echo "  test         Test/verify your fingerprint recognition"
    echo "  fetch-fw     Re-download and extract the sensor firmware (requires sudo)"
    echo "  reset        Factory-reset / re-pair sensor keys (requires sudo)"
    echo "  setup-pam    Enable fingerprint login in openSUSE PAM (requires sudo)"
    echo "  uninstall    Completely remove flux-vprint and restore PAM (requires sudo)"
    echo "  help         Display this help message"
    echo ""
}

# Main routing
case "${1:-status}" in
    status)
        cmd_status
        ;;
    install)
        cmd_install
        ;;
    enroll)
        cmd_enroll
        ;;
    test|verify)
        cmd_test
        ;;
    fetch-fw|fetch-firmware)
        cmd_fetch_fw
        ;;
    reset)
        cmd_reset
        ;;
    setup-pam)
        cmd_setup_pam
        ;;
    uninstall)
        cmd_uninstall
        ;;
    help|--help|-h)
        cmd_help
        ;;
    *)
        echo -e "${RED}[ERROR]${NC} Unknown command: $1"
        cmd_help
        exit 1
        ;;
esac
