#!/bin/bash

# Optional argument
custom_log_dir="$1"

# Find all wine-related processes
for pid in $(pgrep -x wineserver); do
    # Extract WINEPREFIX from process environment
    prefix=$(tr '\0' '\n' < /proc/$pid/environ | grep '^WINEPREFIX=' | cut -d= -f2)

    # If not set, default to ~/.wine
    if [ -z "$prefix" ]; then
        prefix="$HOME/.wine"
    fi

    # Extract WINELOADER (path to wine binary)
    wine_bin=$(tr '\0' '\n' < /proc/$pid/environ | grep '^WINELOADER=' | cut -d= -f2)

    # If WINELOADER is found, get version
    if [ -n "$wine_bin" ] && [ -x "$wine_bin" ]; then
        version=$("$wine_bin" --version 2>/dev/null)
    else
        #version="unknown"
        continue
    fi

    # Decide where to save logs
    if [ -n "$custom_log_dir" ]; then
        log_dir="$custom_log_dir"
    else
        log_dir="$prefix"
    fi

    # Ensure log directory exists
    # mkdir -p "$log_dir"

    # Ensure prefix exists
    if [ -d "$log_dir" ]; then
        # Write log file inside prefix
        logfile="$log_dir/wine_process_${pid}.log"

        # Skip writing if file already exists
        if [ -f "$logfile" ]; then
            echo "Log file $logfile already exists, skipping..."
            continue
        fi

        {
            echo "PID: $pid"
            echo "Prefix: $prefix"
            echo "Wine Binary: $wine_bin"
            echo "Wine Version: $version"
            echo "Timestamp: $(date)"
            echo ""
            echo "---- Environment ----"
            tr '\0' '\n' < /proc/$pid/environ
            echo "---------------------"
        } > "$logfile"

        # Keep only the last 5 logs, delete older ones
        find "$log_dir" -maxdepth 1 -type f -name 'wine_process_*.log' -printf '%T@ %p\0' \
        | sort -z -n \
        | head -z -n -5 \
        | cut -d' ' -f2- --zero-terminated \
        | xargs -0 rm -f
    fi
done
