#!/bin/bash
DIRECTORY="$(readlink -f "$(dirname "$0")")"

function error {
  echo -e "\e[91m$1\e[39m"
  exit 1
}

#ensure settings dir exists
if [ ! -d "${DIRECTORY}/data/settings" ];then
  echo "creating settings directory"
  mkdir -p "${DIRECTORY}/data/settings"
  #create default files inside
  echo '' > "${DIRECTORY}/data/settings/reinstall-after-update"
fi

if [ ! -f ~/.local/share/applications/pi-apps-settings.desktop ];then
  echo "Creating Settings menu button"
  echo "[Desktop Entry]
Name=Pi Apps Settings
Comment=Configure Pi-Apps or create an App
Exec=${DIRECTORY}/settings
Icon=${DIRECTORY}/icons/logo.png
Terminal=false
Type=Application
Categories=Settings;" > ~/.local/share/applications/pi-apps-settings.desktop
  
fi

settings='show-edit-button
update-always
reinstall-after-update
'

tooltips='When viewing an App'\''s details, display an Edit button. Beware that updating will revert your edits.
Instead of checking for updates once a day, do an update check every time Pi-Apps is launched.
If the app was installed prior to updating, then automatically install it back after updating it.
'
line=1
for i in $settings
do
  if [ -f "${DIRECTORY}/data/settings/${i}" ];then
    truefalse='true'
  else
    truefalse='false'
  fi
  LIST="${LIST}${truefalse}
$(echo "$settings" | sed -n "${line}p" )
$(echo "$tooltips" | sed -n "${line}p" )
"
  line=$((line+1))
done
LIST="${LIST::-1}"
#echo "LIST: ${LIST}EOL"

output="$(echo -e "$LIST" | yad --center --title='Pi-Apps Settings' --width=310 --height=300 --no-headers \
  --list --checklist --separator='\n' --window-icon="${DIRECTORY}/icons/logo.png" \
  --column=:CHK --column=Name --column=tip:HD --tooltip-column=3 --print-column=2 \
  --button='new app'!"${DIRECTORY}/icons/create.png":"${DIRECTORY}/createapp" \
  --button=Cancel!"${DIRECTORY}/icons/exit.png":1 \
  --button=Save!"${DIRECTORY}/icons/check.png":0 \
  2>/dev/null)"

button=$? #get exit code to determine which button was pressed
#exit if save was not clicked
[ $button -ne 0 ]&&exit 0

#reformat output var. Only lists items that have been enabled.
output="$(echo "$output" | sed '/^$/d')
"

echo "Output: ${output}EOO"

for i in $settings
do
  #if output matches current setting
  if [ ! -z "$(echo "$output" | grep -x "$i")" ];then
    echo "$i is enabled"
    #create file
    echo '' > "${DIRECTORY}/data/settings/${i}"
  else
    echo "$i is disabled"
    #delete file
    rm -f "${DIRECTORY}/data/settings/${i}"
  fi
done