#!/bin/bash

# Start Auto Clicker on the existing desktop display
set -euo pipefail

# Configuration
UPDATE_ON_START=${UPDATE_ON_START:-1} # Always pull clean code by default

# Move to app directory
cd /home/ubuntu/auto_clicker

# Always update to clean code (discard local changes and pull)
if [ "$UPDATE_ON_START" = "1" ] && command -v git >/dev/null 2>&1 && git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
	echo "Updating repository..."
	echo "Discarding local changes..."
	git reset --hard
	git clean -fd
	echo "Pulling latest code..."
	git fetch --prune
	git reset --hard origin/main
	
	# Reset permissions after pulling code
	echo "Setting file permissions..."
	chmod +x start_app.sh
	chmod +x deploy_ec2.sh
fi

# Ensure we have a display and authority
if [ -z "${XAUTHORITY:-}" ] && [ -f "/home/ubuntu/.Xauthority" ]; then
	export XAUTHORITY=/home/ubuntu/.Xauthority
fi

if [ -z "${DISPLAY:-}" ]; then
	# Try common displays and sockets
	for candidate in :1 :0 :2 :10 :11 :12; do
		if DISPLAY="$candidate" xdpyinfo >/dev/null 2>&1; then
			export DISPLAY="$candidate"; break
		fi
	done
	if [ -z "${DISPLAY:-}" ] && compgen -G "/tmp/.X11-unix/X*" > /dev/null; then
		for sock in /tmp/.X11-unix/X*; do
			num=${sock##*/X}; candidate=":$num"
			if DISPLAY="$candidate" xdpyinfo >/dev/null 2>&1; then export DISPLAY="$candidate"; break; fi
		done
	fi
fi

echo "Starting on DISPLAY=${DISPLAY:-<unset>} XAUTHORITY=${XAUTHORITY:-<unset>} as $(whoami)"

if ! xdpyinfo >/dev/null 2>&1; then
	echo "❌ No working X display. Ensure VNC desktop is running."
	exit 1
fi

# Activate venv and run app
source venv/bin/activate
exec python3 main.py

