#!/usr/bin/bash
# Helper script for stap@.service to compile scripts on demand
# Usage: stap-service-prepare SCRIPT_NAME

set -e

SCRIPT_NAME="$1"
if [ -z "$SCRIPT_NAME" ]; then
    echo "Usage: $0 SCRIPT_NAME" >&2
    exit 1
fi

KRELEASE=$(uname -r)
SCRIPT_PATH="/etc/systemtap/script.d"
MODULE_PATH="/lib/modules/$KRELEASE/systemtap"
CACHE_PATH="/var/cache/systemtap"
STAP="/usr/bin/stap"

STP_FILE="$SCRIPT_PATH/$SCRIPT_NAME.stp"
KO_FILE="$MODULE_PATH/$SCRIPT_NAME.ko"
OPTIONS_FILE="$SCRIPT_PATH/$SCRIPT_NAME.options"

# Create necessary directories
mkdir -p "$MODULE_PATH"
mkdir -p "$CACHE_PATH"

# Source options file if it exists
STAP_OPTIONS=""
if [ -f "$OPTIONS_FILE" ]; then
    . "$OPTIONS_FILE"
fi

# Check if .stp file exists
if [ ! -f "$STP_FILE" ]; then
    echo "Script file not found: $STP_FILE" >&2
    exit 1
fi

# Check if recompilation is needed
# Recompile if: .ko doesn't exist OR .stp is newer than .ko
if [ ! -f "$KO_FILE" ] || [ "$STP_FILE" -nt "$KO_FILE" ]; then
    echo "Compiling $SCRIPT_NAME.stp to $SCRIPT_NAME.ko..."

    # Compile in cache directory to avoid clutter
    cd "$CACHE_PATH"
    "$STAP" -p4 -m "$SCRIPT_NAME" $STAP_OPTIONS "$STP_FILE"

    # Move compiled module to final location
    mv "$SCRIPT_NAME.ko" "$KO_FILE"
    echo "Compilation complete: $KO_FILE"
else
    echo "Using cached module: $KO_FILE"
fi

exit 0
