#!/bin/bash

recursiveExec="edubuntu-menu-admin"

# shellcheck disable=SC2124
args=$@
if ! [ "${args}" = "" ]; then
  # shellcheck disable=SC2206
  selAppArry=($args)
  rm /usr/share/edubuntu/applications/*.desktop
  fileContents=$(cat <<EOF
[Desktop Entry]
NoDisplay=true
EOF
)
  for file in "${selAppArry[@]}"; do
    echo "${fileContents}" > "/usr/share/edubuntu/applications/${file}"
  done
  exit 0
fi

while true; do

iconLs=$(ls /usr/share/applications/)
# shellcheck disable=SC2206
iconLsArry=($iconLs)
iconLs=$(ls /var/lib/snapd/desktop/applications/)
# shellcheck disable=SC2206
iconSnapArry=($iconLs)
iconTableArry=()
for file in "${iconLsArry[@]}"; do
  if [ "${file}" = "defaults.list" ] || [ "${file}" = "mimeinfo.cache" ] \
     || [ "${file}" = "kde-mimeapps.list" ]; then continue; fi
  test=$(grep -i "NoDisplay=true" "/usr/share/applications/${file}")
  if ! [ "${test}" = "" ]; then continue; fi
  if [ -e "/usr/share/edubuntu/applications/${file}" ]; then
    iconTableArry+=("TRUE")
  else
    iconTableArry+=("FALSE")
  fi
  iconTableArry+=("${file}")
  name=$(grep "Name=" "/usr/share/applications/${file}" | cut -d '=' -f 2 | head -n 1)
  iconTableArry+=("${name}")
done
for file in "${iconSnapArry[@]}"; do
  if [ "${file}" = "defaults.list" ] || [ "${file}" = "mimeinfo.cache" ] \
     || [ "${file}" = "kde-mimeapps.list" ]; then continue; fi
  test=$(grep -i "NoDisplay=true" "/var/lib/snapd/desktop/applications/${file}")
  if ! [ "${test}" = "" ]; then continue; fi
  if [ -e "/usr/share/edubuntu/applications/${file}" ]; then
    iconTableArry+=("TRUE")
  else
    iconTableArry+=("FALSE")
  fi
  iconTableArry+=("${file}")
  name=$(grep "Name=" "/var/lib/snapd/desktop/applications/${file}" | cut -d '=' -f 2 | head -n 2 | tail -n 1)
  iconTableArry+=("${name}")
done

selectedIcons=$(zenity --width=800 --height=600 \
  --title "Edubuntu Menu Administration" \
  --window-icon=/usr/share/icons/hicolor/scalable/apps/edubuntu-menu-admin.svg \
  --list \
  --checklist \
  --separator=" " \
  --text="Select applications to hide for non-administrator users" \
  --ok-label="Apply (Password Required)" \
  --cancel-label="Close" \
  --column="Hidden" \
  --column="Filename" \
  --column="Application Name" \
  "${iconTableArry[@]}")
exitCode=$?

if [ "${exitCode}" = "1" ]; then exit 0; fi

# shellcheck disable=SC2206
selectedArry=($selectedIcons)

# shellcheck disable=SC2068
pkexec "${recursiveExec}" ${selectedArry[@]}

done
