#!/bin/bash 

LOGFILE="/var/log/chromium-monitor.log"

# Function to log messages with timestamps
log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOGFILE"
}

# Function to get the monitor value from DHCP
get_monitor() {
    sudo cat /var/lib/dhcp/* | grep -a "option monitor" | tail -1 | \
    awk '{ s = ""; for (i = 3; i <= NF; i++) s = s $i " "; print s}' | \
    awk -F '"' '{print $2}'
}

# Function to get the current window name
get_current_window() {
    DISPLAY=:0 xdotool getwindowfocus getwindowname
}

# Initialize monitor variable
monitor=""
while [ -z "$monitor" ]; do
    monitor=$(get_monitor)
    if [ -n "$monitor" ]; then
        log "Initial monitor detected: $monitor"  # Log initial monitor
    fi
    sleep 5
done

# Main loop to continuously check the current window
while true; do
    current_window=$(get_current_window)  # Get the current window name

    if [ -n "$current_window" ]; then
        # Check for mismatch using case-insensitive comparison
        if ! echo "$current_window" | grep -iq "$monitor"; then
            log "Mismatch detected! Monitor: $monitor, Current: $current_window"
            log "Rebooting now."
            sudo reboot
            exit 1
        fi
    fi

    # Sleep for a short duration before the next check
    sleep 5
done

# Version 1.0:
# Created 2024 by Tim Eertmoed, Christian Hampp @ WiS IT-Solutions GmbH, Germany to work on Raspbian as custom PXE init script.
