#!/bin/bash
# MVGAL DKMS Installer
#
# Installs the MVGAL kernel module via DKMS for automatic rebuilds on kernel updates.
#
# Usage: mvgal-dkms-installer.sh [install|remove|status]
#
# SPDX-License-Identifier: MIT

set -e

# Configuration
MVGAL_MODULE_NAME="mvgal"
MVGAL_VERSION="0.2.7"
INSTALL_DIR="/usr/src"
TEMP_DIR="/tmp/mvgal-dkms-install-$$"
LOG_FILE="/var/log/mvgal-dkms-install.log"

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

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1" | tee -a "$LOG_FILE"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1" | tee -a "$LOG_FILE"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1" | tee -a "$LOG_FILE"
}

error_exit() {
    log_error "$1"
    cleanup
    exit 1
}

cleanup() {
    rm -rf "$TEMP_DIR"
}

check_privileges() {
    if [ "$(id -u)" -ne 0 ]; then
        if command -v pkexec >/dev/null 2>&1; then
            log_info "Requesting elevated privileges via pkexec..."
            exec pkexec "$0" "$@"
        else
            error_exit "This installer requires root privileges and pkexec is not installed."
        fi
    fi
}

check_requirements() {
    log_info "Checking system requirements..."

    # Check for DKMS
    if ! command -v dkms >/dev/null 2>&1; then
        error_exit "DKMS is not installed. Please install dkms package."
    fi

    # Check for git
    if ! command -v git >/dev/null 2>&1; then
        error_exit "Git is not installed. Please install git package."
    fi

    # Check for build tools
    if ! command -v make >/dev/null 2>&1; then
        error_exit "Make is not installed."
    fi

    # Check kernel headers
    KERNEL_VERSION=$(uname -r)
    if [ ! -d "/lib/modules/${KERNEL_VERSION}/build" ]; then
        error_exit "Kernel headers for ${KERNEL_VERSION} not found. Please install kernel headers."
    fi

    log_info "System requirements satisfied"
}

download_source() {
    log_info "Downloading MVGAL source..."

    mkdir -p "$TEMP_DIR"
    cd "$TEMP_DIR"

    # Check for git
    if command -v git >/dev/null 2>&1; then
        if git clone --depth 1 --branch "v${MVGAL_VERSION}" \
            "https://github.com/TheCreateGM/mvgal.git" \
            "mvgal-${MVGAL_VERSION}" 2>/dev/null; then
            log_info "Source downloaded successfully"
            return 0
        fi
    fi

    error_exit "Failed to download MVGAL source"
}

prepare_dkms() {
    log_info "Preparing DKMS module structure..."

    local src_dir="${TEMP_DIR}/mvgal-${MVGAL_VERSION}"
    local dkms_dir="${INSTALL_DIR}/${MVGAL_MODULE_NAME}-${MVGAL_VERSION}"

    # Remove existing installation
    if [ -d "$dkms_dir" ]; then
        log_info "Removing existing DKMS source..."
        rm -rf "$dkms_dir"
    fi

    # Copy source to DKMS location (only kernel module)
    mkdir -p "$dkms_dir"
    cp -r "$src_dir/kernel/"* "$dkms_dir/"
    cp "$src_dir/kernel/dkms/dkms.conf" "$dkms_dir/"

    # Update dkms.conf with correct version
    sed -i "s/PACKAGE_VERSION=.*/PACKAGE_VERSION=\"${MVGAL_VERSION}\"/" "$dkms_dir/dkms.conf"

    log_info "DKMS structure prepared"
}

install_dkms() {
    log_info "Building and installing DKMS module..."

    # Remove any existing DKMS installation
    if dkms status mvgal 2>/dev/null | grep -q "$MVGAL_VERSION"; then
        log_info "Removing existing DKMS module..."
        dkms remove mvgal/$MVGAL_VERSION --all 2>/dev/null || true
    fi

    # Add to DKMS
    log_info "Adding module to DKMS..."
    dkms add -m mvgal -v "$MVGAL_VERSION"

    # Build module
    log_info "Building kernel module..."
    dkms build -m mvgal -v "$MVGAL_VERSION"

    # Install module
    log_info "Installing kernel module..."
    dkms install -m mvgal -v "$MVGAL_VERSION"

    log_info "DKMS module installed successfully"
}

remove_dkms() {
    log_info "Removing DKMS module..."

    if ! dkms status mvgal 2>/dev/null | grep -q "$MVGAL_VERSION"; then
        log_info "Module not installed via DKMS"
        return 0
    fi

    # Remove
    dkms remove mvgal/$MVGAL_VERSION --all

    # Remove source
    rm -rf "${INSTALL_DIR}/${MVGAL_MODULE_NAME}-${MVGAL_VERSION}"

    log_info "DKMS module removed successfully"
}

show_status() {
    dkms status mvgal
}

main() {
    # Initialize log
    echo "=== MVGAL DKMS Install Log ===" > "$LOG_FILE"
    echo "Started: $(date)" >> "$LOG_FILE"

    # Check privileges
    check_privileges "$@"

    # Handle commands
    case "${1:-install}" in
        install)
            check_requirements
            download_source
            prepare_dkms
            install_dkms
            ;;
        remove)
            remove_dkms
            ;;
        status)
            show_status
            ;;
        *)
            echo "Usage: $0 [install|remove|status]"
            exit 1
            ;;
    esac

    cleanup
    echo "Completed: $(date)" >> "$LOG_FILE"
}

main "$@"
