#!/bin/bash
#Simple Yad Frontend for Quickemu/Quickget

#!/bin/bash

# Select target folder
current_folder=$(pwd)

target_folder=$(yad \
 --file \
 --directory \
 --filename=current_folder \
 --width="640" \
 --center \
 --title="Quickget ISO Target Folder" \
 --text="<b>Select ISO Target Directory</b>" \
 --image="/usr/local/share/icons/custom/vm_app.png" \
 --borders="24" \
 --window-icon="/usr/local/share/icons/custom/vm.png" 
 
)

cd $target_folder

# If cancel is selected or window closed stop script
if [ ! -d "$target_folder" ]; then
    yad --error --title=" Quickget ISO Target Error!" --window-icon=youtube --image=dialog-error \
    --center --width=640 --no-buttons  \
    --text="Target folder is not valid: $target_folder"
    exit 1
fi
############

# Warn about list creation delay
(yad\
 --width=640\
 --title="Quickget ISO Selector"\
 --window-icon="/usr/local/share/icons/custom/vm.png"\
 --center\
 --image=gtk-dialog-info\
 --borders="24"\
 --no-buttons\
 --text="Please Wait, it will take a few seconds for the ISO list to load..."\
 --wrap\
 --timeout="7"\
 --timeout-indicator="bottom"
)

# Read quickget output into an array
mapfile -t quickget_list < <(quickget --list)

# Read array from file

# Add "false" elements before each array element
for i in "${quickget_list[@]}"; do
    yad_list+="false|"$i"|"
done

# Change internal field separator from default to custom value
OLDIFS="$IFS" 
IFS='|'

# ISO selection UI
ISO=$(yad \
 --title="Quickget ISO Selector" \
 --class="AVLinux-quickget" \
 --image="/usr/local/share/icons/custom/vm_app.png" \
 --window-icon="/usr/local/share/icons/custom/vm.png" \
 --height="640" \
 --width="400" \
 --borders="24" \
 --center \
 --separator="" \
 --list \
 --radiolist \
 --print-column=2 \
 --column="Select" \
 --column="ISO" \
 --button="Download":0 \
${yad_list[@]}
)

# Reset default internal field separator to default
IFS="$OLDIFS"

# Moves to terminal to observe download (Terminology options used)
terminology -T="Quickget Downloading Selected ISO..." -e "tycat /usr/local/share/icons/custom/AVL-FileActions.png && echo ""Retrieving Selected ISO..."" && quickget "$ISO"" 

# Text info about how to run VM
(yad\
 --width="640"\
 --title="Quickget ISO Selector"\
 --window-icon="/usr/local/share/icons/custom/vm.png"\
 --center\
 --close-on-unfocus\
 --window-icon="/usr/local/share/icons/custom/vm.png"\
 --image=gtk-dialog-info\
 --no-buttons\
 --text="If successful you can now launch your downloaded VM by right-clicking on its '.conf' file and 'Open With' Quickemu Launcher."\
 --wrap \
 --timeout="12"\
 --timeout-indicator="bottom"
)

exit 0