#!/bin/bash
# Keep-screen-alive wrapper for player
# Prevents screen from locking/turning off while player is running

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Function to keep screen awake
keep_screen_awake() {
    while true; do
        # Move mouse slightly to prevent idle
        if command -v xdotool &> /dev/null; then
            xdotool mousemove_relative 1 1
            xdotool mousemove_relative -1 -1
        fi
        
        # Disable DPMS and screensaver periodically
        if command -v xset &> /dev/null; then
            xset s reset
            xset dpms force on
        fi
        
        sleep 30
    done
}

# Function to inhibit systemd sleep (if available)
inhibit_sleep() {
    if command -v systemd-inhibit &> /dev/null; then
        # Run player under systemd inhibit to prevent sleep
        systemd-inhibit --what=sleep --why="Signage player running" \
            bash "$SCRIPT_DIR/start.sh"
        return $?
    fi
    return 1
}

# Try systemd inhibit first (most reliable)
if inhibit_sleep; then
    exit 0
fi

# Fallback: Start keep-alive in background
keep_screen_awake &
KEEPALIVE_PID=$!

# Start the player
cd "$SCRIPT_DIR"
bash start.sh
PLAYER_EXIT=$?

# Kill keep-alive when player exits
kill $KEEPALIVE_PID 2>/dev/null || true

exit $PLAYER_EXIT
