#!/bin/bash

recursiveEx="ubuntustudio-installer" # Used for debugging

_autoRemovePkgFn () {
  # shellcheck disable=SC2124
  _meta=$@
  _pkg=$(apt-cache depends "${_meta}" | grep ":" | cut -d ":" -f 2 | cut -c 2-)
  # shellcheck disable=SC2206
  _pkgArry=(${_pkg})
  # shellcheck disable=SC2068
  for i in ${!_pkgArry[@]}; do
    if [ "${_pkgArry[i]}" = "386" ]; then
      unset '_pkgArry[i]'
    fi
  done
  # shellcheck disable=SC2068
  for _mark in ${_pkgArry[@]}; do
    apt-mark auto "${_mark}" || true
  done

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

# Before we begin, let's make sure the cache is updated
qapt-batch --update

while true; do

(
  echo 10; sleep 1
  echo 20; sleep 1
  echo 30; sleep 1
  echo 40; sleep 1
  echo 50; sleep 1
  echo 60; sleep 1
  echo 70; sleep 1
  echo 80; sleep 1
  echo 90; sleep 1
  echo 100; sleep 1
) | zenity --progress \
  --title="Please Wait" \
  --width=600 \
  --text="Building Package Table..." \
  --percentage=0 \
  --auto-close \
  --no-cancel &

# List or packages to potentially install
declare -a pkgListArry=(
[0]="linux-lowlatency"
[1]="ubuntustudio-lowlatency-settings"
[2]="ubuntustudio-performance-tweaks"
[3]="ubuntustudio-audio"
[4]="ubuntustudio-graphics"
[5]="ubuntustudio-photography"
[6]="ubuntustudio-publishing"
[7]="ubuntustudio-video"
[8]="ubuntustudio-wallpapers"
[9]="ubuntustudio-menu"
[10]="ubuntu-edu-music"
)

pkgTable=()
# shellcheck disable=SC2068
for pkg in ${pkgListArry[@]}; do
  if dpkg -s "${pkg}" &> /dev/null; then
    pkgInst="TRUE"
  else
    pkgInst="FALSE"
  fi
  pkgTable+=("${pkgInst}")
  pkgTable+=("${pkg}")
  if [ "${pkg}" = "linux-lowlatency" ]; then
    pkgDesc="Low-Latency Ubuntu Linux Kernel"
  else
    pkgDesc=$(apt-cache search "${pkg}" | head -n 1 | sed -e "s/${pkg} - //g")
  fi
  pkgTable+=("${pkgDesc}")
done

textMsg="Select or deselect package(s) to modify installation status.\n\
NOTE: Installing ubuntustudio-pulseaudio-config will remove the\n\
pipewire configuration and vice-versa."

selectedPkg=$(zenity \
  --title="Ubuntu Studio Installer" \
  --window-icon=/usr/share/icons/hicolor/scalable/apps/ubuntustudio-installer.svg \
  --width=800 \
  --height=600 \
  --list \
  --multiple \
  --checklist \
  --separator=" " \
  --text="${textMsg}" \
  --ok-label="Modify Installed Package Selection" \
  --cancel-label="Close" \
  --column "Installed" \
  --column "Metapackage" \
  --column "Description" \
  "${pkgTable[@]}");
selExit=$? 

if [ -z "${selectedPkg}" ]; then
 if [ "${selExit}" = "1" ]; then exit 0; fi
fi

# shellcheck disable=SC2206
selectedArry=($selectedPkg)

selPkgNotinst=()
# shellcheck disable=SC2068
for pkg in ${selectedArry[@]}; do
  if dpkg -s "${pkg}" &> /dev/null; then
    true
  else
    selPkgNotinst+=("${pkg}")
  fi
done

instSelPkgFn () {
  if [ -x /usr/bin/qapt-batch ]; then
    qapt-batch --install --qwindowtitle "Ubuntu Studio Installer" "${selPkgNotinst[@]}"
    # shellcheck disable=SC2068
    for pkg in ${selPkgNotinst[@]}; do
      if [ "${pkg}" = "ubuntustudio-audio" ]; then
        pkexec /usr/sbin/ubuntustudio-installer-fix
          zenity \
            --title "Ubuntu Studio Installer" \
            --window-icon=/usr/share/icons/hicolor/scalable/apps/ubuntustudio-installer.svg \
            --width "200" \
            --warning \
            --text "Please log-out and log-in for proper audio configuration to take effect."
      fi
    done
  fi
}

instSelPkgConfFn () {
    # shellcheck disable=SC2128
    warnStr=$(cat <<EOF
The following packages will be installed by this action:

${selPkgNotinst[@]}

You may be asked for your password more than once.
Do you wish to continue?
EOF
)
  zenity \
  --title "Ubuntu Studio Installer" \
  --window-icon=/usr/share/icons/hicolor/scalable/apps/ubuntustudio-installer.svg \
  --width "600" \
  --height "400" \
  --question \
  --text "${warnStr}" \
  --ok-label "Continue" \
  --cancel-label "Skip/Go Back"
}

if [ -n "${selPkgNotinst[0]}" ]; then
  if instSelPkgConfFn; then
    instSelPkgFn
  fi
fi

# shellcheck disable=SC2206
unselArry=(${pkgListArry[@]})
# shellcheck disable=SC2068
for sel in ${selectedArry[@]}; do
  for i in "${!unselArry[@]}"; do
    # shellcheck disable=SC2053
    if [[ ${unselArry[i]} = $sel ]]; then
      unset 'unselArry[i]'
    fi
  done
done

unSelPkginst=()
# shellcheck disable=SC2068
for pkg in ${unselArry[@]}; do
  if dpkg -s "${pkg}" &> /dev/null; then
    unSelPkginst+=("${pkg}")
  fi
done

removeConfirmFn () {
  warnStr=$(cat <<EOF
The following packages may be removed by this action:

${uninstDepRecInl[@]}

If you do not wish to have any one of these individual packages removed,
simply reinstall them. No settings are being removed by uninstallation.
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.
EOF
)
  zenity \
  --title "Ubuntu Studio Installer" \
  --window-icon=/usr/share/icons/hicolor/scalable/apps/ubuntustudio-installer.svg \
  --width "600" \
  --height "400" \
  --question \
  --text "${warnStr}" \
  --ok-label "Continue" \
  --cancel-label "Skip/Go Back"
}


if [ -n "${unSelPkginst[0]}" ]; then
  _uninstDepRec=$(apt-cache depends "${unSelPkginst[0]}" | grep ":" | cut -d ":" -f 2 | cut -c 2-)
  # shellcheck disable=SC2206
  uninstDepRecArry=(${_uninstDepRec})
  for i in "${!uninstDepRecArry[@]}"; do
    if [ "${uninstDepRecArry[i]}" = "386" ]; then
      unset 'uninstDepRecArry[i]'
    fi
  done
  # shellcheck disable=SC2068
  uninstDepRecInl=$(echo ${uninstDepRecArry[@]} | fmt -w 80)
  if removeConfirmFn; then
    # shellcheck disable=SC2068
    pkexec "${recursiveEx}" ${unSelPkginst[@]} | \
      zenity --progress --auto-close --no-cancel --pulsate
  fi
fi

done
