#!/bin/bash

# Dynamic Scan for Machine Learning Models version 0.1.
#
# Copyright (c) 2025 Oracle, Inc.
# Licensed under the Universal Permissive License v 1.0 as shown at 
# https://oss.oracle.com/licenses/upl/

cat "$1" | awk '
    # Handle open and openat system calls
    /open(at)?\(/ {
        # Extract PID and FD from the open/openat call
        if (match($0, /^ *([0-9]+)\s+.*open(at)?\([^)]*\)\s+=\s+([0-9]+)/, arr)) {
            pid = arr[1]
            fd = arr[3]
            open_fd[pid " " fd] = 1  # Store as a combined key using space as separator
        }
    }
    # Handle read system calls
    /read\(/ {
        # Extract PID and FD from the read call
        if (match($0, /^ *([0-9]+)\s+read\(([0-9]+)/, arr)) {
            pid = arr[1]
            fd = arr[2]
            if (open_fd[pid " " fd]) {  # Access the array using the concatenated key with space
                print $0
            }
        }
    }
    # Handle write system calls
    /write\(/ {
        # Extract PID and FD from the write call
        if (match($0, /^ *([0-9]+)\s+write\(([0-9]+)/, arr)) {
            pid = arr[1]
            fd = arr[2]
            if (open_fd[pid " " fd]) {  # Access the array using the concatenated key with space
                print $0
            }
        }
    }
'

# Then filter out lines that match read/write syscalls without corresponding open syscalls
cat "$1" | grep -Pv '^[0-9]+\s+(read|write)\('
