#!/bin/bash
#Simple yad script to search for everything (Files, Installed apps, web), created by PPC, for antiX Linux; GPL license, please keep this attribution-- version 1 final
#Support for programme localisation by Wallon.
#NOTE: Web search requires the package "ddgr" to be installed, script also requires "yad"
#Advised toolbar entry, to run this application in IceWM window manager is something like this:
#prog "Finder" /usr/share/icons/papirus-antix/48x48/actions/document-preview-archive.png finder


TEXTDOMAINDIR=/usr/share/locale
TEXTDOMAIN=finder

###Text shown in the script (for easy localization/edition, it’s placed in variables) (mv_)= memory variable:
mv_you_need_to_have=$"You need to have yad installed. Please make sure it is installed and re-run this script"
mv_nothing_to_do=$"Nothing to do"
mv_finder=$"Finder"
mv_not_empty_continuing=$"not empty, continuing"
mv_no_results_found_for_files=$"No results found for files/folders with names containing this expression, in "
mv_x=$"Exit"
mv_COMMAND_could_not_be=$"COMMAND could not be found"
mv_is_a_command=$"is a command meant to be run from the terminal"
mv_there_are_instalable_packages=$"There are instalable packages that match that query, available in the Repository (and their version): "
mv_no_results_found_for_this_application=$"No results found for this application or setting:"
mv_internet_ok=$"Internet: ok"
mv_download_ddgr=$"Finder requires ddgr to perform web searches.\n Do you want to install it (it is a 40kb download)? \n Note: after the instalation, Finder will have to be restarted."
mv_OK=$" OK "
mv_ddgr_not_installed=$"ddgr not installed!"
mv_search_parameter_is_empty=$"Search parameter is empty, exiting"
mv_no_region=$"No region (results are shown in English)"
mv_the_current_region_code=$"The current Region code for web searches is:"
mv_it_will_be_replaced=$"It will be replaced by:"
mv_starting_finder=$"starting Finder"
mv_language=$"Language"
mv_new_search=$"New search"
mv_Files_2=$"Files"
mv_Apps_Settings_4=$"Apps/Settings"
mv_Web_44=$"Web"
mv_Run=$"Run"
mv_terminal_command=$"(Terminal command)"
mv_no_region_short_text=$"No region"
mv_running_warning=$"WARNING: Closing this terminal window will close also the $query instance running inside it!"
mv_message=$"Press any key to close this terminal window"
mv_searching=$"Searching, please wait"
mv_cloud_drive_warning=$"A Remote cloud drive may be mounted. If it is, it will be searched. \n This may greatly increase the time it takes to get results (from a few seconds to a several minutes)!"
mv_mounted_partitions_warning=$"There are mounted partitions or drives, other than your Home folder (ex: USB flash drives,etc). \n Finder will automatically search there too.\n This process may be much slower than just searching in your home folder (it may take several minutes).\n \n What do you want to do?\n "
mv_install_tgpt_text=$"Do you want to Install TGP?\n It's required to use this feature\n NOTE: After the terminal window that installs tgp closes, Finder will have to be restarted"
mv_save_answer=$"Save answer"
mv_files_column_text=$"Double left click the file you want to open (or click here to re-order the results)"
mv_apps_column_text=$"Double left click the app you want to run/select it and click $mv_Run (or click here to re-order the results)"
mv_modified=$"Last modified in:"
mv_size=$"Size: "
mv_save_file_text=$"Choose the file name and where to save it"
gpt=$"GPT"


# Adding a (hopefully) unique string to the output files to avoid over-writing in concurrent runs:
#fix_unique="$(tr -dc 'A-Za-z0-9' </dev/random | head -c 13; echo)" # Random alpha-numeric string
fix_unique="$(whoami)_$(tr -dc 'A-Za-z0-9' </dev/random | head -c 13; echo)" # User-name Random alpha-numeric string

# Define some (more) output file(s) using the unique prefix:
resultados="/tmp/${fix_unique}_resultado.txt"
al_finalos="/tmp/${fix_unique}_finished1"
salida_yad="/tmp/${fix_unique}_yad"
lista_exec="/tmp/${fix_unique}_list_of_execs.txt"
instaltemp="/tmp/${fix_unique}_instalable"
# Prefix for some output files:
lista_temp="/tmp/${fix_unique}_list"
query_result="/tmp/${fix_unique}_finder_result"

#check for dependencies: yad
if ! [ -x "$(command -v yad)" ]; then
 x-terminal-emulator -e whiptail --title "$mv_finder" --msgbox "$mv_you_need_to_have" 8 78
 exit 1
fi

kill_finder()
{
  # Kill any previous Finder window:
  # TODO/FIXME?: Should one replace 'Finder' with the translation string?
  
  kill_em="$(xprop -name Finder _NET_WM_PID 2>/dev/null)" # Probably to be replaced?
  if [ -n "${kill_em}" ]; then
    sleep 0.8
    kill ${kill_em}
  #else
  #  echo "Nothing to kill (yet)!"
  fi
} # kill_finder

file_finder()
{
	export -f  kill_finder
#Simple FILE SEARCH GUI, using yad:
kill_finder # close any previous window
#get user input
file=$(sed '1q;d' "${salida_yad}"| sed s'/.$//')

#if file is empty, exit the script
if [[ $file -eq 25 ]]; then
exit
fi

#If no user input, exit script
[[ -z "$file" ]] && { echo "$mv_nothing_to_do" ; exit 1; }

#Check for common cloud drives and display warning that cloud drives are searched and that it may take several minutes (user can exit the script or continue)
if pgrep -x "rclone" > /dev/null; then
 yad --window-icon=/usr/share/icons/Adwaita/48x48/legacy/preferences-system-search-symbolic.symbolic.png --center --width=450 --title="$mv_finder" --text="$mv_cloud_drive_warning" --button="$mv_x":2 --button="$mv_OK":1
 foo=$?
 [[ $foo -eq 2 ]] && exit 0
fi

#If if other partitions/disks are mounted and warn user that they will be searched (and that it may take some time)
search_only_in_home=0
mounted_partitions=$(df -h | awk 'NR>1 {print $6}'| grep "^/media/")
if [ -z "$mounted_partitions" ]; then
  result="No partitions are currently mounted."
else
 yad --window-icon=/usr/share/icons/Adwaita/48x48/legacy/preferences-system-search-symbolic.symbolic.png --center --width=450 --title="$mv_finder" --text="$mv_mounted_partitions_warning"  --button=$"Search only in my Home folder":4 --button=$"Continue":1 --button="$mv_x":2
 foo=$?
 #user selects to exit
 [[ $foo -eq 2 ]] && exit 0
  #user selects to search only in the home folder
 [[ $foo -eq 4 ]] && search_only_in_home=1
fi

#Show a yad progress window
yad --progress-text="$mv_searching" --width=400 --window-icon=/usr/share/icons/Adwaita/48x48/legacy/preferences-system-search-symbolic.symbolic.png --center --title="Finder" --no-buttons --progress --pulsate &

#Search for what the user inputed:, by default, only inside the user's home folder  -printf "  ▷ %p %Cc\n"
find "$HOME" -iname "*$file*" -printf "%p    ▷ $mv_modified %Cc, $mv_size ~%k kb \n" > "$query_result" && sleep 0.4
#If user did not select to search only i▷n the home folder, try to search also in the /media folder (to search also mounted drives, like flash-drives, etc)
[[ $search_only_in_home -eq "0" ]] && find /media -iname "*$file*"  -printf "%p    ▷ $mv_modified %Cc, $mv_size ~%k kb \n" >> "$query_result"

#Close yad progress window (by searching by it's title and closing it)
sleep 0.8 && kill $(xprop -name Finder _NET_WM_PID| awk '{print $3}')
	
#Warn if no results and if so, exit:
var=$(cat "$query_result" )
if [ -n "$var" ]; then
  echo "$mv_not_empty_continuing"
else
     yad  --window-icon=/usr/share/icons/Adwaita/48x48/legacy/preferences-system-search-symbolic.symbolic.png --center --width=300 --title="$mv_finder" --text="$mv_no_results_found_for_files $HOME: \n $file" --button="$mv_x" --fixed
  exit
fi

#show search results
	var=$(yad --button="$mv_x":1 --window-icon=/usr/share/icons/Adwaita/48x48/legacy/preferences-system-search-symbolic.symbolic.png --title="$mv_finder"  --height=500 --width=1000 --center  --separator=" " --list  --column="$mv_files_column_text"  < "$query_result")
	# Define the character to stop at
	stop_char="▷"
	# Use parameter expansion to extract the substring until the stop character
	substring="${var%%$stop_char*}"
	var=$substring
#process user selection
trail=${var##*[^[:blank:]]}    # get trailing space
var=${var%${trail}}            # remove trailing space
#open selected file
xdg-open "$var"
} # file_finder

app_finder()
{
#Simple yad script to search for executables (from availables .desktop files), list and launch them
kill_finder # close any previous window

#get user input
query=$(sed '1q;d' "${salida_yad}"| sed s'/.$//')
#If no input, exit script
[[ -z "$query" ]] && { query="*"; }

### wait for a button to be pressed then perform the selected function
foo=$?

[[ $foo -eq 2 ]] && exit 0

#Show a yad progress window
yad --progress-text="$mv_searching" --width=400 --window-icon=/usr/share/icons/Adwaita/48x48/legacy/preferences-system-search-symbolic.symbolic.png --center --title="Finder" --no-buttons --progress --pulsate &

#Find matching .desktop files, save results in \tmp\resultado.txt
##################################################################################
#get current localization
#lang="$(locale | grep LANG | cut -d= -f2 | cut -d_ -f1)"
lang="$(locale | grep LANG | cut -d= -f2 | cut -d. -f1)"
#hack to fix languages that are identified by only 2 characters, and not 4 (or more)
#comparing text that's before the "_" to the text that after that, converted to lower case, if it matches, use only the letters before the "_"
l1=$(echo "$lang" |cut -d_ -f1)
l2=$(echo "$lang" |cut -d_ -f2)
l2_converted=$(echo "${l2,,}")
if [ $l1 = $l2_converted ]; then lang=$l1; fi

##clean up temporary files
:> "${resultados}"
#rm "${instaltemp}"
:> "${lista_exec}"

#look for the searched query in all files in /usr/share/applications/, searching name, genericname, comments (in the default language and in the current language) 
grep "^Exec.*$query" -Eril /usr/share/applications/ | sort -t: -u -k1,1 > "${resultados}"
grep -roil -m 1 "^Name\[$lang\]=.*$query" /usr/share/applications/ >> "${resultados}"
grep -roil -m 1 "^Name=.*$query" /usr/share/applications/ >> "${resultados}"
grep -roil -m 1 "^GenericName\[$lang\]=.*$query" /usr/share/applications/ >> "${resultados}"
grep -roil -m 1 "^GenericName=.*$query" /usr/share/applications/ >> "${resultados}"
grep -roil -m 1 "^Comment\[$lang\]=.*$query" /usr/share/applications/ >> "${resultados}"
grep -roil -m 1 "^Comment=.*$query" /usr/share/applications/ >> "${resultados}"
#Search in ~/.local/share/applications too
grep "^Exec.*$query" -Eril ~/.local/share/applications | sort -t: -u -k1,1 >> "${resultados}"
grep -roil -m 1 "^Name\[$lang\]=.*$query" ~/.local/share/applications >> "${resultados}"
grep -roil -m 1 "^Name=.*$query" ~/.local/share/applications >> "${resultados}"
grep -roil -m 1 "^GenericName\[$lang\]=.*$query" ~/.local/share/applications >> "${resultados}"
grep -roil -m 1 "^GenericName=.*$query" ~/.local/share/applications >> "${resultados}"
grep -roil -m 1 "^Comment\[$lang\]=.*$query" ~/.local/share/applications >> "${resultados}"
grep -roil -m 1 "^Comment=.*$query" ~/.local/share/applications >> "${resultados}"

#remove empty spaces and organize lines
sed -i '/\S/!d' file "${resultados}"
sort -o "${resultados}" -u "${resultados}"

###################################################################################
# Get exec localized names and exec fields
for file in $(cat "${resultados}")
do
 name1=$(grep -o -m 1 '^Name=.*' $file)
 exec=$(grep -o -m 1 '^Exec=.*' $file)
 terminal=$(grep -o -m 1 '^Terminal=.*' $file)
 if [ $terminal = "Terminal=true" ] ; then exec="desktop-defaults-run -t $exec "
 fi 

 ### localized menu entries generator (slows the script down, but produces nearly perfectly localized menus):
    name2=$name1
 translated_name1=$(grep -o -m 1 "^Name\[$lang\]=.*" $file)
 [ -z "$translated_name1" ] && note="No localized name found, using the original one" || name2=$translated_name1
 #if the desktop file has the string "Desktop Action" simply use the original untranslated name, to avoid risking using a translation that's not the name of the app
 grep -q "Desktop Action" $file && name2=$name1
 name1=$name2
 ### end of localized menu entries generator	 
 name=$(echo $name1|sed 's/.*\=//') 
 ##only add line if name is not an empty string and the arrow (or just spaces and the arrow)- this may happen if flatpaks are installed and you search for "flatpak":
 name_contents=$(echo "$name"| sed 's/ //g')
 name_length=${#name_contents}
 [ "$name_length" == "0" ] && result="it's an empty line, don't include it"|| echo "$name""	"  ▷ "$exec"
 ##always add the exec field to a secondary temporary file, to later check if terminal commands are already listed by script, in order to add them, if needed:
 echo "$exec" >> "${lista_exec}"
done > "${lista_temp}.txt"

#remove the text "Exec=" from the result, so it looks better
sed -i -e 's/Exec=//g' "${lista_temp}.txt"
#sort lines in the file to a sorted new file
sort "${lista_temp}.txt" > "${lista_temp}-sorted.txt"

##Start of: Check if the query is a valid terminal command...
if command -v $query &> /dev/null; then
    #... and if it is, checks if the query is NOT already listed in the file. If it isn't, add it:
	if ! grep -iw "$query" "${lista_exec}"; then
		echo "$query $mv_terminal_command""	"  ▷ "x-terminal-emulator -e $query" >> "${lista_temp}-sorted.txt"
	fi
fi ###...end of: Check if the query is a valid terminal command

sleep 0.5
#Close yad progress window (by searching by it's title and closing it)
kill $(xprop -name Finder _NET_WM_PID)

#Warn if no results...:
var=$(cat "${lista_temp}.txt" )
if [ -n "$var" ]; then
  echo "$mv_not_empty_continuing"
else

#If no results, check if search is for a terminal only command and warn user
	if ! command -v $query &> /dev/null; then
    echo "$mv_COMMAND_could_not_be"
		else
	#run the command	
    x-terminal-emulator -e /bin/bash -c "echo '$mv_running_warning' & $query && read -p '$mv_message' x"
     exit
	fi

#If no results, check if query exists in the Repository, available for instalation, and warn user about that:
   apt list *$query* > "${instaltemp}"
   instalable_options=$(cat "${instaltemp}"| tail -n +2 )
   [[ -z "$instalable_options" ]] && { instalable_warning=""; } || { instalable_warning="\n \n $mv_there_are_instalable_packages \n $instalable_options"; }
    yad --window-icon=/usr/share/icons/Adwaita/48x48/legacy/preferences-system-search-symbolic.symbolic.png --center --width=300 --title="$mv_finder" --text="$mv_no_results_found_for_this_application \n $query $instalable_warning" --button="$mv_x" --fixed
    exit
fi ### end of Warning user of lack of results

#If only one match, run that command without asking and exit:
if { IFS='' read -r result && ! read -n 1 _; } <"${lista_temp}.txt"; then
command="${var#*▷}"			   # use only command to the right of the arrow symbol
#remove any %U, %u, %F or %f on the end of the command, that some exec fields have and cause errors when launching the executable
command=$(echo $command | sed -e "s/ %U//g")
command=$(echo $command | sed -e "s/ %u//g")
command=$(echo $command | sed -e "s/ %F//g")
command=$(echo $command | sed -e "s/ %f//g")
#run the command
eval "$command"
exit
fi

#Show results, so user can select one
var=$(yad --button="$mv_x":1 --button="▷ $mv_Run":2 --window-icon=/usr/share/icons/Adwaita/48x48/legacy/preferences-system-search-symbolic.symbolic.png --title="$mv_finder"  --height=500 --width=1000 --center  --separator=" " --list  --column="$mv_apps_column_text"  < "${lista_temp}-sorted.txt")
#Parse the user selection:
trail=${var##*[^[:blank:]]}    # get trailing space
var=${var%${trail}}            # remove trailing space
command="${var#*▷}"			   # use only command to the right of the arrow symbol
#remove any %U, %u, %F or %f on the end of the command, that some exec fields have and cause errors when launching the executable
command=$(echo $command | sed -e "s/ %U//g")
command=$(echo $command | sed -e "s/ %u//g")
command=$(echo $command | sed -e "s/ %F//g")
command=$(echo $command | sed -e "s/ %f//g")
#run the command
eval "$command"

} # app_finder

web_finder1()
{
#get user input
query=$(sed '1q;d' /tmp/yad| sed s'/.$//')
yad --center --text="Opening browser in https://duckduckgo.com/html?q=$query" 
#If nothing was entered, exit the script
[[ -z "$query" ]] && { echo "Search parameter is empty, exiting" ; exit 1; }

#Perform the query on the default web browser:

desktop-defaults-run -b  "https://duckduckgo.com/html?q=$query"
	
}

web_finder()
{
# Script to perform web searches using DuckDuckGo (using the ddgr command) and show the results in a yad window
kill_finder # close any previous window

#Connectivity check:
ip=$(hostname -I)
if [ -n "$ip" ]; then
 echo "$mv_internet_ok"
else
 yad --center --timeout=4  --title="$mv_finder" --picture --filename=/usr/share/icons/Adwaita/48x48/legacy/network-error.png --geometry=300x100-50-50 --inc=256 --button="$mv_x" --timeout-indicator=bottom  --undecorated --close-on-unfocus --escape-ok --skip-taskbar
exit
fi

## testing for dependency and, in antiX, try to install it, if user so selects
	if ! [ -x "$(command -v ddgr)" ]; then
	app="ddgr"
	install_apps=1
	fi
			
	if [[ "$install_apps" -eq 1 ]]; then
	 yad --title="$mv_finder" --center --text="$mv_download_ddgr" --button="$mv_OK":1 --button="$mv_x":2 
	 foo=$?
	 #This next line zeroes the file that is used to flag the end of the install process (in the end of the follwoing if statement, the "; echo 1 > "${al_finalos}" part changes that's file's content, signaling that the process is over and the main script can continue running:
	 echo 0 > "${al_finalos}"
		if [[ $foo -eq 1 ]]; then x-terminal-emulator -e /bin/bash -c "gksu 'apt update' && gksu 'apt install -y ddgr'; echo 1 > "${al_finalos}""
		fi
	 #wait until install process is finished (this waits until the "sudo apt install" process running in paralel echoes the value 1 to the "${al_finalos}" file:
finished=$(cat "${al_finalos}")
until [ $finished -gt 0 ]
do
finished=$(cat "${al_finalos}")
done
# Restart the script
exec bash "$0" "$@"
		fi

#test if install of each one of the dependencies was succefull, if not, exit:
	if ! [ -x "$(command -v ddgr)" ]; then	 yad --title="$mv_finder" --center --text="$mv_ddgr_not_installed" --button="$mv_x" --image="/usr/share/icons/papirus-antix/48x48/emblems/vcs-conflicting.png"
	 exit
	fi
#### end of dependencies check and install process	

#get user input
query=$(sed '1q;d' "${salida_yad}"| sed s'/.$//')

#If nothing was entered go to the websearch configuration window
#[[ -z "$query" ]] && { query=$(xclip -out); }
[[ -z "$query" ]] && { echo "$mv_search_parameter_is_empty"; websearch_config; }

#Show a yad progress window
yad --progress-text="$mv_searching" --width=400 --window-icon=/usr/share/icons/Adwaita/48x48/legacy/preferences-system-search-symbolic.symbolic.png --center --title="Finder" --no-buttons --progress --pulsate &

#Get region to perform the serch, from the previous user selection:
region=$(cat ~/.config/finder_web_search_config| cut -d'>' -f1)
#If no region was selected, use the default "wt-wt"
[[ -z "$region" ]] && { region="wt-wt"; }

#perform the search, using ddgr  ### Please check https://duckduckgo.com/duckduckgo-help-pages/settings/params/ for the "REGION" (the -r parameter). wt-wt is for "no region"; pt-pt is for Portugal, etc
ddgr --np -n20 -x -r $region $query > "${query_result}_0"

filename="${query_result}_0"
# Get the number of characters in the file
file_size=$(wc -c < "$filename")

# Check size of ddgr results (workaround for ddgr not working):
if [ "$file_size" -lt 10 ]; then
		#The result is less than 10 characters, this means ddgr is not working:
		kill_finder # close any previous window
		desktop-defaults-run -b  \"https://duckduckgo.com/html?q=$query\"
		#sleep 1
		yad  --fixed --title="$mv_finder" --window-icon=/usr/share/icons/Adwaita/48x48/legacy/preferences-system-search-symbolic.symbolic.png --center --text=$" Finder could not display your web search using it's ddgr window! \n Results were shown in the default browser!\n Sorry for the inconvenience" --button="$mv_x":1

	else
#The result is 10 characters or more, this means ddgr is working, so the results will be displayed in a yad window:
#Split very big lines (but don't split very long words because they probably are web addresses)
cat ${query_result}_0 | fmt -100 > "${query_result}_websearch.txt"

kill_finder # close any previous window

#display text, with clickable links
yad  --title="$mv_finder"   --window-icon=/usr/share/icons/Adwaita/48x48/legacy/preferences-system-search-symbolic.symbolic.png --center --width=800  --height=650 --button=" $mv_language":3 --button=" ⌕ $mv_new_search":2 --button="$mv_x":1 --text-info <  "${query_result}_websearch.txt" --show-uri --fontname="ubuntu 12"

#Listen for user selection:
foo=$?

#IF user clicked the button on the results window:
if [[ $foo -eq 1 ]]; then
  exit
fi

if [[ $foo -eq 2 ]]; then
 main_window
fi

if [[ $foo -eq 3 ]]; then
  if [ ! -f ~/.config/finder_web_search_config ]; then
    region="$mv_no_region"
  else
    region=$(cat ~/.config/finder_web_search_config| cut -d'>' -f1)
  fi
  websearch_config
fi


fi

} # web_finder

websearch_config()
{
region_list="wt-wt  > $mv_no_region_short_text, xa-ar  > Arabia, xa-en  > Arabia (en), ar-es  > Argentina, au-en  > Australia, at-de  > Austria, be-fr  > Belgium (fr), be-nl  > Belgium (nl), br-pt  > Brazil, bg-bg  > Bulgaria, ca-en  > Canada, ca-fr  > Canada (fr), ct-ca  > Catalan, cl-es  > Chile, cn-zh  > China, co-es  > Colombia, hr-hr  > Croatia, cz-cs  > Czech Republic, dk-da  > Denmark, ee-et  > Estonia, fi-fi  > Finland, fr-fr  > France, de-de  > Germany, gr-el  > Greece, hk-tzh  > Hong Kong, hu-hu  > Hungary, in-en  > India, id-id  > Indonesia, id-en  > Indonesia (en), ie-en  > Ireland, il-he  > Israel, it-it  > Italy, jp-jp  > Japan, kr-kr  > Korea, lv-lv  > Latvia, lt-lt  > Lithuania, xl-es  > Latin America, my-ms  > Malaysia, my-en  > Malaysia (en), mx-es  > Mexico, nl-nl  > Netherlands, nz-en  > New Zealand, no-no  > Norway, pe-es  > Peru, ph-en  > Philippines, ph-tl  > Philippines (tl), pl-pl  > Poland, pt-pt  > Portugal, ro-ro  > Romania, ru-ru  > Russia, sg-en  > Singapore, sk-sk  > Slovak Republic, sl-sl  > Slovenia, za-en  > South Africa, es-es  > Spain, se-sv  > Sweden, ch-de  > Switzerland (de), ch-fr  > Switzerland (fr), ch-it  > Switzerland (it), tw-tzh  > Taiwan, th-th  > Thailand, tr-tr  > Turkey, ua-uk  > Ukraine, uk-en  > United Kingdom, us-en  > United States, ue-es  > United States (es), ve-es  > Venezuela, vn-vi  > Vietnam"
region=$(cat ~/.config/finder_web_search_config| cut -d'>' -f1)

#If no region, show that currently the default value is selected
[[ -z "$region" ]] && { region=$mv_no_region; }
if [ "$region" = "wt-wt" ]; then region=$mv_no_region; fi


 local=$(echo $region_list)
selection=$(yad --center  --text="$mv_the_current_region_code \n $region \n $mv_it_will_be_replaced" --window-icon=/usr/share/icons/Adwaita/48x48/legacy/preferences-system-search-symbolic.symbolic.png --title="$mv_finder" \
--image="/usr/share/icons/papirus-antix/48x48/categories/applications-system.png" \
--form --date-format="%-d %B %Y" --separator="," --item-separator="," \
--field="":CBE \
"$local")
choice=${selection::-1}
#touch ~/.config/finder_web_search_config
echo "$choice" > ~/.config/finder_web_search_config
main_window
	
} # websearch_config

interact_with_gpt()
{
	
	#Connectivity check:
ip=$(hostname -I)
if [ -n "$ip" ]; then
 echo "$mv_internet_ok"
else
 yad --center --timeout=4  --title="$mv_finder" --picture --filename=/usr/share/icons/Adwaita/48x48/legacy/network-error.png --geometry=300x100-50-50 --inc=256 --button="$mv_x" --timeout-indicator=bottom  --undecorated --close-on-unfocus --escape-ok --skip-taskbar
exit
fi


## testing for dependency and, in antiX, try to install it, if user so selects
	if ! [ -x "$(command -v tgpt)" ]; then
	app="tgpt"
	install_apps=1
	fi

	if [[ "$install_apps" -eq 1 ]]; then
	 yad --title="$mv_finder" --center --text="$mv_install_tgpt_text" --button="$mv_OK":1 --button="$mv_x":2 
	 foo=$?
	 #This next line zeroes the file that is used to flag the end of the install process (in the end of the follwoing if statement, the "; echo 1 > /tmp/finished1" part changes that's file's content, signaling that the process is over and the main script can continue running:
	 echo 0 > /tmp/finished1
		if [[ $foo -eq 1 ]]; then x-terminal-emulator -e /bin/bash -c  'curl -sSL https://raw.githubusercontent.com/aandrew-me/tgpt/main/install | bash -s /usr/local/bin > /tmp/finished1'
		fi
		if [[ $foo -eq 2 ]]; then exit
		fi
		##wait until install process is finished (this waits until the "install" process running in paralel echoes the value 1 to the /tmp/finished1 file:
		#finished=$(cat /tmp/finished1)
		#until [ ${finished} -gt 0 ]; do
		#finished=$(cat /tmp/finished1)
		#done
		while true; do
		#if instalation finished (in this particular case, the install process running in paralel finally outputs "tgpt -h"), exit the do-done loop and continue with the script
			if grep -q "tgpt" "/tmp/finished1"; then  break;  fi
		done
		# Restart the script
		exec bash "$0" "$@"

	fi


###Main part of the function: Process query using tgpt
[[ -z "$query" ]] && { input_text="Tell me something random, not about honey"; } || input_text=$(sed '1q;d' "${salida_yad}"| sed s'/.$//')
    
    #if no input, exit
    #  [[ -z "$input_text" ]] && exit 
      
#Show a yad progress window
yad --progress-text="$mv_searching" --width=400 --window-icon=/usr/share/icons/Adwaita/48x48/legacy/preferences-system-search-symbolic.symbolic.png --center --title="Finder" --no-buttons --progress --pulsate &

# Send the input to TGPT and receive a response
response=$(echo "$input_text" | tgpt -w)
                
#Close yad progress window (by searching by it's title and closing it)
sleep 0.4
kill $(xprop -name Finder _NET_WM_PID)

#always store the result of the gtp query on a temporary file (if not done here, then it has to be done on the start of the if-fi that saves the result...)
echo "$response" > "${query_result}_gtp.txt"

# Display the response in a dialog box
yad --center --title="Finder" --form --width=700 --height=500 --field="$gpt::TXT" "$response" --width=600 --height=800 --button="$mv_save_answer":4 --button="$mv_new_search":3 --button="$mv_x"
        
#User choose to save result to a file: 
foo=$?
		if [[ $foo -eq 4 ]]; then
			file=$(yad --center --file --save --title="$mv_save_file_text")
			cp "${query_result}_gtp.txt" "$file"
			exit
		fi
#User choose new search		
		if [[ $foo -eq 3 ]]; then
			main_window
		fi
} # interact_with_gpt

main_window()
{
#Toggle the script off if already running (prevents file search running on empty, if user runs a second instance of the script) 
#This is great if user is running the script from a taskbar icon, for example, and clicking it twice, to toggle on/off the search window.
if pidof -x "finder" >/dev/null; then
  echo "$mv_starting_finder"
else
  kill_finder # close any previous window
  exit
fi

#clean temporary file
:> "${salida_yad}"
#Draw main window and get user input from search field and from buttons, using --on-top flag because of the default fluxbox configuration:
yad --title="$mv_finder"  --on-top --width=400 --image=/usr/share/icons/Adwaita/48x48/legacy/preferences-system-search-symbolic.symbolic.png --text="" --borders=10 --mouse --undecorated --close-on-unfocus --escape-ok --skip-taskbar --form --field="" --button="⌕ $mv_Files_2":2  --button="⌕ $mv_Apps_Settings_4":4 --button="⌕ $mv_Web_44":44  --button="⌕ $gpt":66 > "${salida_yad}"
foo=$? && echo $foo >> "${salida_yad}"
query=$(sed '1q;d' "${salida_yad}"| sed s'/.$//')
button=$(sed '2q;d' "${salida_yad}")

#run selected action, acording to the selected button
# 0 is when no button is pressed- the script interprets that as doing a file search for the text entered:
if [[ $button -eq 0 ]]; then
  file_finder
fi

if [[ $button -eq 2 ]]; then
  file_finder
fi

if [[ $button -eq 4 ]]; then
  app_finder
fi

if [[ $button -eq 44 ]]; then
  web_finder
fi	

if [[ $button -eq 66 ]]; then
  interact_with_gpt
fi	
} # main_window

#Export variables, so they can be called from the main window buttons
export -f file_finder app_finder web_finder main_window websearch_config interact_with_gpt kill_finder

#Execute main_window function, when the script starts
main_window
