#!/usr/bin/bash

SetupDir="/usr/local/pengwin-setup.d"

export VERSION="1.2a"

# shellcheck disable=SC1090
source ${SetupDir}/common.sh "$@"

declare CANCELLED
declare SKIP_UPDATES
declare JUST_UPDATE

rm -f "${HOME}"/.should-restart

# define functions

function check_upgrades() {
  echo "Updating package database"

  # shellcheck disable=SC2155
  local debian_security_ok="$(cat /etc/apt/sources.list 2>&1 | grep -c "https://deb.debian.org/debian-security testing/updates")"
  if [[ ${debian_security_ok} != 0 ]]; then
    sudo sed -i 's$debian-security testing/updates$debian-security testing-security$g' /etc/apt/sources.list
  fi

  update_packages --allow-releaseinfo-change

  # Check for .dist-upgrade file in /etc/apt and inform user dist-upgrade available if so
  if [[ -f "/etc/apt/.dist-upgrade" ]]; then
    echo "Distribution upgrade flag noticed! Alerting user"
    if (confirm --title "Upgrade Available" --yesno "A distribution upgrade is available. In addition to regular package upgrades, this may also install / remove packages. Would you like to continue?\n\nTo run a non-automated distribution upgrade and see package changes, or to perform this in your own time, run 'sudo apt-get dist-upgrade'" 12 90); then
      sudo rm /etc/apt/.dist-upgrade
      sudo apt-get dist-upgrade -y
    fi
  fi

  # Check if there's any upgrades to pengwin-setup / pengwin-base
  echo "Running upgrade check..."
  # shellcheck disable=SC2155
  local upgrd_check="$(sudo apt-get upgrade --show-upgraded --assume-no | grep pengwin)"
  if [[ "${upgrd_check}" == *"pengwin"* ]]; then
    echo "Pengwin core package upgrades found"
    if (confirm --title "Upgrades Available" --yesno "Updates have been detected for Pengwin core packages. Would you like to update them? This is highly recommended. Note: Pengwin-setup will close after installation complete." 10 91); then

      # Ensure that packages get updated without affecting other held packages like udev
      sudo apt-mark unhold pengwin-base pengwin-setup >/dev/null 2>&1
      upgrade_packages pengwin-base pengwin-setup
    fi
  elif [[ ${JUST_UPDATE} ]]; then
    upgrade_packages 
  fi

  if [[ -z ${WSL2} && "${upgrd_check}" == *"libqt5"* ]]; then
    # If WSL1 we patch libQt5Core.so
    sudo strip --remove-section=.note.ABI-tag /usr/lib/x86_64-linux-gnu/libQt5Core.so.5 >/dev/null 2>&1
  fi
}

function WelcomePrompt() {
  message --title "Welcome to Pengwin" --msgbox "Thank you for supporting sustainable independent open source development.\n
Pengwin comes with a core set of useful packages pre-installed, such as curl, git, and wslu.\n
pengwin-setup allows you to install additional hand-curated selections for Pengwin and configure optional WSL-specific settings. \n
Many more packages are available via the apt package manager and optional pip, npm, and RubyGems package managers." 17 80
}

function continue_prompt() {
  if (confirm --title "Continue setup?" --yesno "Would you like to continue pengwin-setup?" 8 45); then
    echo "Starting pengwin-setup."
  else
    echo "Exiting pengwin-setup."
    echo "You may run the script again any time by running: $ pengwin-setup"
    exit 0
  fi
}

function ByeMessage() {
  if [[ -f "${HOME}"/.should-restart ]]; then
    local should_restart=0
    rm -f "${HOME}"/.should-restart
  fi

  if [[ ${WIN_CUR_VER} -ge 17763 && ${should_restart} ]]; then
    message --title "Setup is complete." --msgbox "This window will be closed to apply the changes in the environment.\nPlease start Pengwin again \n\nYou may rerun pengwin-setup any time by typing: $ pengwin-setup\n\nYou may open a browser link to get help any time by typing: $ pengwin-help" 14 80

    if [[ ${#CMD_MENU_OPTIONS[*]} == 0 ]]; then #No automated installation
      wslconfig.exe /t "${WSL_DISTRO_NAME:-WLinux}"
    fi
  elif [[ ${should_restart} ]]; then
    message --title "Setup is complete." --msgbox "Please close this window and start Pengwin again to apply the changes in the environment.\n\nYou may rerun pengwin-setup any time by typing: $ pengwin-setup\n\nYou may open a browser link to get help any time by typing: $ pengwin-help" 14 80
  else
    message --title "Setup is complete." --msgbox "You may rerun pengwin-setup any time by typing: $ pengwin-setup\n\nYou may open a browser link to get help any time by typing: $ pengwin-help" 10 80
  fi
}

# main menu
function install_menu() {
  # shellcheck disable=SC2155
  local menu_choice=$(

    menu --title "pengwin-setup" --checklist --separate-output "\nHand-curated add-ons [SPACE to select, ENTER to confirm]:" 16 99 8 \
      "EDITORS" "Install text editors neovim, emacs, or Visual Studio Code (requires X)    " off \
      "GUI" "Install an X server or various other GUI applications" off \
      "MAINTENANCE" "Various maintenance tasks like home backup" off \
      "PROGRAMMING" "Install various programming languages support" off \
      "SERVICES" "Enable services support (SSH, rc.local)" off \
      "SETTINGS" "Change various settings in Pengwin" off \
      "TOOLS" "Install applications or servers" off \
      "UNINSTALL" "Uninstall applications and packages installed by pengwin-setup" off

    # shellcheck disable=SC2188
    3>&1 1>&2 2>&3
  )

  echo "Selected:" "${menu_choice}"

  if [[ ${menu_choice} == "${CANCELLED}" ]]; then
    return
  fi

  local exit_status

  if [[ ${menu_choice} == *"EDITORS"* ]]; then
    echo "EDITORS"
    bash ${SetupDir}/editors.sh "$@"
    exit_status=$?
  fi

  if [[ ${menu_choice} == *"GUI"* ]]; then
    echo "GUI"
    bash ${SetupDir}/gui.sh "$@"
    exit_status=$?
  fi

  if [[ ${menu_choice} == *"MAINTENANCE"* ]]; then
    echo "MAINTENANCE"
    bash ${SetupDir}/maintenance.sh "$@"
    exit_status=$?
  fi

  if [[ ${menu_choice} == *"PROGRAMMING"* ]]; then
    echo "PROGRAMMING"
    bash ${SetupDir}/programming.sh "$@"
    exit_status=$?
  fi

  if [[ ${menu_choice} == *"SERVICES"* ]]; then
    echo "SERVICES"
    bash ${SetupDir}/services.sh "$@"
    exit_status=$?
  fi

  if [[ ${menu_choice} == *"SETTINGS"* ]]; then
    echo "SETTINGS"
    bash ${SetupDir}/settings.sh "$@"
    exit_status=$?
  fi

  if [[ ${menu_choice} == *"TOOLS"* ]]; then
    echo "TOOLS"
    bash ${SetupDir}/tools.sh "$@"
    exit_status=$?
  fi

  if [[ ${menu_choice} == *"UNINSTALL"* ]]; then
    echo "UNINSTALL"
    bash ${SetupDir}/uninstall.sh "$@"
    exit_status=$?
  fi

  if [[ ${exit_status} != 0 ]]; then
    install_menu "$@"
  fi
}

### Main
if [[ ${JUST_UPDATE} ]]; then
  check_upgrades
  exit 0
fi

WelcomePrompt
continue_prompt

if [[ ! ${SKIP_UPDATES} ]]; then
  check_upgrades
fi

# Ensure our packages are held to prevent odd situation of
# being updated while running other operations from pengwin-setup
# install menu
echo "Holding pengwin-base & pengwin-setup to ensure no changes while operating"
sudo apt-mark hold pengwin-base pengwin-setup >/dev/null 2>&1

sudo apt-mark unhold libc6 >/dev/null 2>&1

install_menu "$@"

# Unhold our packages
echo "Unholding pengwin-base & pengwin-setup"
sudo apt-mark unhold pengwin-base pengwin-setup >/dev/null 2>&1

ByeMessage
exit 0
