#!/bin/bash

if [[ $XDG_SESSION_TYPE != "x11" ]]; then
	echo "Unsupported session type: $XDG_SESSION_TYPE"
	exit 1
fi

get_tg_window_id(){
	tg_window_id=$(wmctrl -lx | grep telegram-desktop | awk '{print $1}')
}

get_mouse_location(){
	mouse_xy=$(xdotool getmouselocation --shell)
	mouse_x=$(printf "%s\n" "$mouse_xy" | grep X= | cut -d= -f2)
	mouse_y=$(printf "%s\n" "$mouse_xy" | grep Y= | cut -d= -f2)
}

return_mouse(){
	xdotool mousemove $mouse_x $mouse_y
}

lock_tg(){
	xdotool windowactivate --sync $tg_window_id key ctrl+l
}

read_passcode(){
	if [[ ! -f $HOME/.local/.tgpasscode ]]; then
		echo "Passcode file not found!, Enter Telegram local passcode seperated characters by space."
		echo "Example: If passcode is 1234, then enter 1 2 3 4 "
		read -p "Enter passcode: " PASSCODE
		echo $PASSCODE > $HOME/.local/.tgpasscode
		echo Telegram Passcode saved at: $HOME/.local/.tgpasscode
	fi
	tgpasscode=$(cat $HOME/.local/.tgpasscode)
}

unlock_tg(){
	xdotool windowactivate --sync $tg_window_id key $tgpasscode Return
}

if [ "$1" == "lock" ]; then
	get_tg_window_id
	get_mouse_location
	lock_tg
	return_mouse
elif [ "$1" == "unlock" ]; then
	read_passcode
	get_tg_window_id
	get_mouse_location
	unlock_tg
	return_mouse
else
	echo "Invalid argument. Please use 'lock' or 'unlock'."
	exit 1
fi
