#!/bin/bash

#======== INI VARIABLES ========
# Change these in the INI file

#======== GLOBAL VARIABLES =========
declare -g mrsampath="/media/fat/Scripts/.MiSTer_SAM"
declare -g misterpath="/media/fat"
declare -g joychange="/tmp/.SAM_tmp/Joy_Change"
declare -g keychange="/tmp/.SAM_tmp/Key_Change"
declare -g key_activity_file="/tmp/.SAM_tmp/SAM_Keyboard_Activity"
declare -g joy_activity_file="/tmp/.SAM_tmp/SAM_Joy_Activity"
declare -g mouse_activity_file="/tmp/.SAM_tmp/SAM_Mouse_Activity"

#======== DEBUG VARIABLES ========
samquiet="Yes"
samdebug="No"
samtrace="No"

#======== LOCAL VARIABLES ========
samtimeout=60
menuonly="Yes"

#========= PARSE INI =========
# Read INI, Check for mount point presence
while ! test -d /media/fat/
do
	sleep 1
	count=`expr $count + 1`
	if test $count -eq 30; then
		echo " Mount timed out!"
      		exit 1
 		fi
done

#Set up SAM paths
[ ! -d "/tmp/.SAM_List" ] && mkdir /tmp/.SAM_List/ 
[ ! -d "/tmp/.SAM_tmp" ] && mkdir /tmp/.SAM_tmp/

if [ -f "${misterpath}/Scripts/MiSTer_SAM.ini" ]; then
	source "${misterpath}/Scripts/MiSTer_SAM.ini"
fi


#======== FUNCTIONS ========
function sam_jschange() {
	# Reset trigger file
	echo "" |>"$joychange"
	# Monitor joystick devices for changes
	inotifywait --quiet --monitor --event create --event delete /dev/input --include js --outfile "$joychange" 2>/dev/null &
}

function sam_keybchange() {
	# Reset trigger file
	echo "" |>"$keychange"
	# Monitor keyboard devices for changes
	inotifywait -r --quiet --monitor --event create --event delete /dev/input/ --include by-path --outfile "$keychange" 2>/dev/null &
}


function input_clear() {
	# Reset activity triggers
	echo "" |>"$joy_activity_file"
	echo "" |>"$mouse_activity_file"
	echo "" |>"$key_activity_file"
}

function sam_trigger() {
	if [ "$(/bin/find "$joy_activity_file" -mmin +${samtimeout})" ] && [ "$(/bin/find "$mouse_activity_file" -mmin +${samtimeout})" ] && [ "$(/bin/find "$key_activity_file" -mmin +${samtimeout})" ]; then				
	input_clear
		if [ "$(ps aux | grep -ice "[M]iSTer_SAM_on")" == "0" ] && [ "$(ps aux | grep -ice [u]pdate)" == "0" ]; then
			echo " No activity detected for ${samtimeout} minutes. SAM starting..."
			/media/fat/Scripts/MiSTer_SAM_on.sh start
			echo " Returned from SAM."
		fi
	input_clear
	fi
}

function sam_jsmonitor() {

	declare -a jsdevices=()
	declare -a excludejoy=()
	declare -a jsnew=()
	
	# Make a list of all js devices on system
	shopt -s nullglob
	for joystick in /dev/input/js*; do
		jsdevices+=( "${joystick}" )
	done
	shopt -u nullglob

	# Exclude motion sensors from monitoring list. This is necessary or else SAM will detect constant input triggers from these js devices
	mapfile -t excludejoy < <(grep -iwns "motion sensors" /proc/bus/input/devices -A 7 | awk -F= '/Handlers/{print $2 }' | awk '/js/{ print $1 }')
	excludejoy=("${excludejoy[@]/#//dev/input/}")
	jsnew=($(comm -3 <(printf "%s\n" "${excludejoy[@]}" | sort) <(printf "%s\n" "${jsdevices[@]}" | sort) | sort -n))

	# Spawn Joystick monitoring process per detected joystick device (excluding motion sensors)
	shopt -s nullglob
	for joystick in ${jsnew[@]}; do
		if [ ! -z "${joystick}" ]; then
			if [ "${samquiet,,}" == "no" ]; then echo " Monitoring controller ${joystick}..."; fi
			"${mrsampath}/MiSTer_SAM_joy.py" "${joystick}" 2>/dev/null &
		fi
	done
	shopt -u nullglob
}

function sam_keybmonitor() {
    local -a kbd_phys_addrs=() # Array to store physical addresses of keyboards

    # PART 1: Find all physical keyboards and collect their addresses.
    for EVENT_DEVICE in /dev/input/event*; do
        [ -e "$EVENT_DEVICE" ] || continue

        local PROPERTIES
        PROPERTIES=$(udevadm info -q property -n "$EVENT_DEVICE")

        # Check if it's a keyboard AND not a virtual device.
        if echo "$PROPERTIES" | grep -q 'ID_INPUT_KEYBOARD=1' && ! echo "$PROPERTIES" | grep -q 'DEVPATH=.*/virtual/.*'; then
            local SYS_PATH
            SYS_PATH=$(echo "$PROPERTIES" | grep 'DEVPATH=')
            SYS_PATH="/sys${SYS_PATH#DEVPATH=}"

            if [ -f "${SYS_PATH}/device/uevent" ]; then
                local phys_addr
                phys_addr=$(grep 'PHYS=' "${SYS_PATH}/device/uevent" | cut -d'=' -f2)

                # BUG FIX: Strip quotes for a clean comparison.
                phys_addr=${phys_addr//\"/}

                if [ -n "$phys_addr" ]; then
                    kbd_phys_addrs+=( "$phys_addr" )
                fi
            fi
        fi
    done

    if [ ${#kbd_phys_addrs[@]} -eq 0 ]; then
        return
    fi

    # PART 2: Find the matching hidraw device for each keyboard address.
    for HIDRAW_DEVICE in /dev/hidraw*; do
        [ -e "$HIDRAW_DEVICE" ] || continue

        local hidraw_name=${HIDRAW_DEVICE##*/}

        if [ -f "/sys/class/hidraw/${hidraw_name}/device/uevent" ]; then
            local hidraw_phys
																	  
					 
            hidraw_phys=$(grep 'HID_PHYS=' "/sys/class/hidraw/${hidraw_name}/device/uevent" | cut -d'=' -f2)
					  
	 

            # BUG FIX: Strip quotes for a clean comparison.
            hidraw_phys=${hidraw_phys//\"/}
				 
																							 
										 

            for kbd_addr in "${kbd_phys_addrs[@]}"; do
                if [ "$hidraw_phys" == "$kbd_addr" ]; then
                    if [ "${samquiet,,}" == "no" ]; then echo "✅ SUCCESS: Linked and monitoring keyboard at $HIDRAW_DEVICE"; fi
                    "${mrsampath}/MiSTer_SAM_keyboard.py" "$HIDRAW_DEVICE" 2>/dev/null &
                    break
                fi
            done
        fi
    done
}

#======== Start ========

# Convert seconds to minutes
samtimeout=$(echo - | awk -v t=${samtimeout} '{print t/60}')


#======== DEBUG OUTPUT =========
if [ "${samtrace,,}" == "yes" ]; then
	echo "********************************************************************************"
	#======== GLOBAL VARIABLES =========
	echo " mrsampath: ${mrsampath}"
	echo " misterpath: ${misterpath}"
	#======== LOCAL VARIABLES ========
	echo " commandline: ${@}"
	echo " samtimeout: ${samtimeout}"
	echo "********************************************************************************"
fi

# Start monitoring for joystick device changes
if [ "${samquiet,,}" == "no" ]; then echo -n " Starting joystick change monitor..."; fi
sam_jschange
if [ "${samquiet,,}" == "no" ]; then echo " Done!"; fi

# Start monitoring for keyboard device changes
if [ "${samquiet,,}" == "no" ]; then echo -n " Starting keyboard change monitor..."; fi
sam_keybchange
if [ "${samquiet,,}" == "no" ]; then echo " Done!"; fi

# Spawn joystick monitoring process per detected joystick device
sam_jsmonitor

# Spawn keyboard monitoring processes
if [[ /dev/input/by-path/*kbd ]]; then
	sam_keybmonitor
fi

# Spawn mouse monitoring process. /dev/input/mice is always present so we don't need to detect changes here
if [ "${samquiet,,}" == "no" ]; then echo " Monitoring mouse activity."; fi
[[ -z $(ps -o pid,args | grep '[M]iSTer_SAM_mouse.sh' | awk '{print $1}' | head -1) ]] && "${mrsampath}/MiSTer_SAM_mouse.sh" 2>/dev/null &

input_clear


#======== MAIN LOOP ========
while :; do
	# If we detect a change to connected joysticks:
	if [ -s "$joychange" ]; then
		#echo " Device change(s) detected!"
		# Wait for devices to stabilize
		sleep 1
		
		# Kill existing Joystick monitors
		for otherpid in $(ps -o pid,args | grep -e '[M]iSTer_SAM_joy.py'| awk '{ print $1 }'); do
			kill -9 ${otherpid}
			wait ${otherpid} &>/dev/null
		done
		
		# Spawn Joystick monitoring processes
		sam_jsmonitor

		# Reset trigger
		echo "" |>"$joychange"
	fi

	
	if [ -s "$keychange" ]; then
		#echo " Device change(s) detected!"
		# Wait for devices to stabilize
		sleep 1
		
		# Kill existing Keyboard monitors
		for otherpid in $(ps -o pid,args | grep -e '[M]iSTer_SAM_keyboard.py'| awk '{ print $1 }'); do
			kill -9 ${otherpid}
			wait ${otherpid} &>/dev/null
		done
		
		# Spawn keyboard monitoring processes
		if [[ /dev/input/by-path/*kbd ]]; then
			sam_keybmonitor
		fi

		# Reset trigger
		echo "" |>"$keychange"
	fi
	
	# Start SAM after input event
	if [ "${menuonly,,}" == "yes" ]; then # Only start SAM from main menu
		# Check if we're at the main menu, wait 1 minute before checking activity
		if [[ "$(cat /tmp/CORENAME)" == "MENU" && "$(/bin/find /tmp/CORENAME -mmin +1)" ]]; then
			# Check activity files against timeout
			echo " Triggered after menuonly=yes"
			sam_trigger
		fi
	else
		# Check activity files against timeout
		if [[ "$(/bin/find /tmp/CORENAME -mmin +1)" ]]; then
			echo " Triggered after menuonly=no"
			sam_trigger
		fi
	fi
sleep 1
done
