#!/bin/bash

_autoRemovePkgFn () {
  _meta=${1}
  _pkg=$(apt-cache depends "${_meta}" | grep "Depends:" | cut -d ":" -f 2)
  for _mark in ${_pkg}; do
    apt-mark auto "${_mark}" || true
  done

  _pkg=$(apt-cache depends "${_meta}" | grep "Recommends:" | cut -d ":" -f 2)
  for _mark in ${_pkg}; do
    apt-mark auto "${_mark}" || true
  done

  apt-get autoremove "${_meta}" -y
}

if [ "${1}" != "" ]; then
  _autoRemovePkgFn "${1}";
fi

while true; do
  _pkgarry="ubuntustudio-audio ubuntustudio-fonts ubuntustudio-graphics ubuntustudio-photography ubuntustudio-publishing ubuntustudio-video"
  _chkarry=""
  for _pkgname in ${_pkgarry}; do
    _chkarry+="$(dpkg --get-selections | grep "${_pkgname}" | cut -f 1 ) "
  done
  _diag="$(cat << _EOF
<html>
<h2><center>Select a feature to uninstall</center></h2>
<p><center>(You will be returned to this dialog)</center></p>
</html>
_EOF
)"
  # shellcheck disable=SC2086
  _meta=$(kdialog --title "Ubuntu Studio Feature Uninstaller"\
    --icon /usr/share/icons/ubuntustudio/places/24/distributor-logo.png\
    --combobox  "${_diag}" ${_chkarry})

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

  _pkg=$(apt-cache depends "${_meta}" | grep "Depends:" | cut -d ":" -f 2)
  _pkg+=$(apt-cache depends "${_meta}" | grep "Recommends:" | cut -d ":" -f 2)

  _diag="<html>
  <h2><center>The following packages may be<br>removed
       by this action:</center></h2>
  <p>If you do not wish to have any one of these individual packages removed,
     simply reinstall them. No settings are being removed
     by uninstallation.</p>
  <p>Additionally, some of these packages may be required by other
     packages and may not be uninstalled, so parts of this list may not
     apply to you.</p>
     This entire metapackage can be easily reinstalled with
     Ubuntu Studio Installer.</p>
  <p><b>Metapackage:<b> <code>${_meta}</code></p>
  <table>
    <tr><td><code>${_pkg}</code></td</tr>
  </table>
  <p><b>Do you wish to continue?</b></p>
</html>"

  if kdialog --title "Ubuntu Studio Feature Uninstaller"\
     --icon /usr/share/icons/ubuntustudio/places/24/distributor-logo.png\
     --warningyesno "${_diag}"; then
    pkexec /usr/bin/ubuntustudio-feat-uninstaller "${_meta}" | zenity --progress --auto-close --no-cancel --pulsate;
  fi
done
