#!/bin/bash

# Detect OS version 
dist=$(lsb_release -si)
ver=$(lsb_release -sr)
nam=$(lsb_release -sc)

WaitWindowReady() {
  local wid=$1
  for i in {1..200}; do
    map_state=$(xprop -id "$wid" WM_STATE 2>/dev/null)
    echo "$map_state" | grep -q "Normal" && return 0
    sleep 0.05
  done
  return 1
}

StartFirefoxApp() {

	#Zenity placement
		id_z=""
	timeout=0
	while [ "$id_z" = "" ]; do 
		sleep 0.01
		id_z=$(xdotool search --onlyvisible --class "zenity" | head -1)
		timeout=$((timeout + 1))
		if [ "$timeout" -gt 100 ]; then
			break
		fi
	done
	WaitWindowReady $id_z
	xdotool windowmove $id_z 0 0


	export DISPLAY=:0
	export MOZ_ENABLE_WAYLAND=0
	export MOZ_WEBRENDER=0
	export MOZ_DISABLE_RDD_SANDBOX=1

	firefox \
	  --kiosk \
	  --no-remote \
	  --new-instance \
	  --disable-session-crashed-bubble \
	  --private-window "$2" &

	pid=$!

	# Wait real window of process
	id=$(xdotool search --sync --onlyvisible --pid $pid | head -1)
	

	# Invisible
	xprop -id $id -f _NET_WM_WINDOW_OPACITY 32c -set _NET_WM_WINDOW_OPACITY 0

	# Wait window mapped
	WaitWindowReady "$id" || {
		echo "Window not ready"
		return 1
	}

	# If < 1 sg --> J1900 with 2 Gb fails 
	sleep 1

	# Remove fullscreen
	wmctrl -ir "$id" -b remove,fullscreen

	# Wait changes applied
	for i in {1..50}; do
		state=$(xprop -id "$id" _NET_WM_STATE)
		echo "$state" | grep -vq FULLSCREEN && break
		sleep 0.05
	done

	# Place & resize
	wmctrl -ir "$id" -e 0,$5,$6,$3,$4
	# Visible
	xprop -id $id -f _NET_WM_WINDOW_OPACITY 32c -set _NET_WM_WINDOW_OPACITY 0xffffffff
}

browser="$1"
if [ "$browser" != "firefox" ]; then
	if ! [ -f /usr/bin/"$1" ]; then
		browser="firefox"
	fi
fi

killall $browser > /dev/null 2>&1

if [ "$browser" = "firefox" ]; then
	if [ $nam = "noble" ]; then
		browser_class="firefox_firefox"
	elif  [ $nam = "precise" ]; then
		browser_class="Firefox"
	else
		browser_class="firefox"
	fi
	StartFirefoxApp $browser_class $2 $3 $4 $5 $6 | zenity --progress --pulsate --auto-close --no-cancel --title="TouchScale" --text="Starting browser..."
	exit 0
fi


if [ "$browser" = "chromium-browser" ]; then
	rm -r /home/pcscale/chromium
	rm -r /home/pcscale/.config/chromium
	$browser --user-data-dir=/home/pcscale/chromium --app=$2  --disable-features=Translate --noerrdialogs --hide-scrollbars --disable-infobars --media-cache-size=1 --disable-background-networking --disable-component-extensions-with-background-pages --dns-prefetch-disabe --disk-cache-size=1 & 
	# class name for Noble (also works on Precise and Bionic).
	browser_class="chromium"
else
	$browser $2 &
	browser_class=$browser
fi

id=""
timeout=0
while [ "$id" = "" ]; do 
	sleep 0.05
	id=$(xdotool search --onlyvisible --class $browser_class | head -1)
	timeout=$((timeout + 1))
	if [ "$timeout" -gt 1000 ]; then
		break
	fi
done

wmctrl -ir $id -b remove,maximized_vert,maximized_horz
xprop -id $id -format _MOTIF_WM_HINTS 32c -set _MOTIF_WM_HINTS 2
xdotool windowsize $id $3 $4
xdotool windowmove $id $5 $6



