#!/bin/bash
set -e

dpkg-maintscript-helper rm_conffile \
  /etc/dconf/profile/user 23.10.11 ubuntustudio-menu -- "$@"

dpkg-maintscript-helper rm_conffile \
  /etc/dconf/profile/ubuntustudio 23.10.12 ubuntustudio-menu -- "$@"

rmAppFoldersFn() {
  echo "Removing GNOME appfolders..."
  varLibDir="/var/lib/ubuntu-appfolder-defaults"
  if ! [ -d "${varLibDir}" ]; then
    return 0
  fi
  if [ -e "${varLibDir}/$1" ]; then
    rm -f "${varLibDir}/$1"
  fi

  dirList=$(ls "${varLibDir}")
  dirListArry=(${dirList})
  folderChildArry=()

  if ! [ "${#dirListArry[*]}" = "0" ]; then
    readFile=$(cat ${varLibDir}/${dirListArry[0]})
    folderChildArry=(${readFile})
    unset 'dirListArry[0]'
    for file in "${dirListArry[@]}"; do
      readFile=$(cat ${varLibDir}/${file})
      readFileArry=(${readFile})
      for i in "${!readFileArry[@]}"; do
        match="no"
        for j in "${!readFileArry[@]}"; do
          if [ "${readFileArry[i]}" = "${folderChildArry[j]}" ]; then
            match="yes"
          fi
        done
        if [ ${match} = "no" ]; then
          folderChildArry+=(${readFileArry[i]})
        fi
      done
    done
  fi

  if ! [ "${#folderChildArry[*]}" = "0" ]; then
    for i in "${!folderChildArry[@]}"; do
     folderChildOut="'${folderChildArry[i]}', ${folderChildOut}"
    done
    folderChildOut=$(echo "${folderChildOut}" | head -c -3)
    output=$(cat <<EOF
[org/gnome/desktop/app-folders]
folder-children=[${folderChildOut}]
EOF
)
    echo "${output}" > /etc/dconf/db/site.d/01_appfolders
  else
    if [ -e /etc/dconf/site.d/01_appfolders ]; then
      rm -f /etc/dconf/site.d/01_appfolders
    fi
  fi

  echo "DONE"
}

case "$1" in
    remove)

if [ -e /etc/dconf/db/site.d/00_edubuntu ]; then
  rm /etc/dconf/db/site.d/00_edubuntu
fi

rmAppFoldersFn edubuntu

if which dconf > /dev/null; then
    dconf update
fi

if [ -e /etc/profile.d/edubuntu.sh ]; then
  rm /etc/profile.d/edubuntu.sh
fi

  update-alternatives \
    --remove default.ubuntu-appfolders /usr/share/dconf/profile/edubuntu

    ;;
esac

# Tag to allow some debhelper commands to inject relevant code
#DEBHELPER#
