#!/bin/bash
#----------------------------------------------------------------
# Description: Linux Lite Upgrade Script - USER
# About: For Linux Lite 5.- Series only
# Licence: GPLv2 Sharing is Caring
# Author: Jerry Bezencon, Ralphy
# Credits: Misko_2083
# Website: https://www.linuxliteos.com
#----------------------------------------------------------------

# Ensure multi-language support
export LANG=C

# Set display output
xhost +
export DISPLAY=:0.0

# Release Upgrade
UPGR="5.8"
UPGRFULL="Linux Lite 5.8"

# Get current Linux Lite version
GETLLVER=$(awk '{print}' /etc/llver)

# Admin user variable
MYUSER=$(sudo -u ${SUDO_USER:-$USER} whoami)

# Linux Lite default dialog icon
ic="/usr/share/icons/Papirus/24x24/apps/liteupgrade.png"		# dialog icon 24x24 PNG

# Application title
APPNAME="Linux Lite Upgrade Utility"

# Log file variables
LOGFILE=/tmp/lite-upgrade.log
REPORTERROR="This error has been logged to $LOGFILE."
if [ -f "$LOGFILE" ]; then chown $MYUSER:$MYUSER $LOGFILE; fi
# log function
log_upgrade(){
    message="$@"
    echo '['$(date +%D\ %H:%M:%S)'] '$message >>$LOGFILE
}
> $LOGFILE
log_upgrade "---------- $APPNAME ----------"

# FIRST LOCAL MODIFICATION HERE

# Set lite-welcome to autostart on first boot - NOW DEFUNCT
LITEWELCOME() {
  echo " "
unset UPDATER
}

# END LOCAL MODIFICATION HERE

REBOOT() {
  log_upgrade "Waiting for restart confirmation..." && log_upgrade "Moving upgrade log to the /var/log/ directory... All done."
    mv -f "$LOGFILE" /var/log/
while (true); do
  # Set dialog icon variable
  THEME=$(xfconf-query -c xsettings -p /Net/IconThemeName)
  if [ -f "/home/$USER/.icons/${THEME}/apps/32/system-reboot.png" ]; then APPICON="/home/$USER/.icons/${THEME}"
  elif [ -f "/usr/share/icons/${THEME}/32x32/apps/system-reboot.svg" ]; then APPICON="/usr/share/icons/${THEME}"
  else APPICON="/usr/share/icons/Papirus"
  fi
  title="$APPNAME"
  exit_type=$(zenity --height="260" --window-icon="$ic" --ok-label="Action" --cancel-label=" " --title="$title" --text='<span font="Sans Bold 10">Upgrade routine completed. Select an option then click Action.</span>\n' \
                     --list --imagelist --print-column=2 --column="  " --column="Action" --column="Description" \
  "$APPICON/32x32/apps/system-reboot.svg" "Restart" "Reboot the computer now" \
  "$APPICON/32x32/apps/system-shutdown.svg" "Shutdown" "Shutdown the computer now" \
  "$APPICON/32x32/apps/accessories-text-editor.svg" "View Log" "View Log now")

  if [ $? -eq "1" ]; then zenity --info --width="300" --title="$APPNAME" --text="\nDon't forget to restart your computer to complete the upgrade."; exit; fi

  # restart and shutdown options
  if [ "$exit_type" = "Restart" ]; then
    systemctl reboot
  elif [ "$exit_type" = "Shutdown" ]; then
    systemctl poweroff
  elif [ "$exit_type" = "View Log" ]; then
    xdg-open /var/log/lite-upgrade.log
  else zenity --info --width="300" --ok-label="Back" --title="$APPNAME" --text="\nPlease choose one of the available options."; continue
  fi
  done
}

LL50() {
# Invoke arrays
ARRAYA=()       # Array for LL 5.0

# check the arch
log_upgrade "Checking Architecture:"
arch=$(uname -m) ; log_upgrade "$arch"

case "$arch" in
    x86)    arch="x86"  ;;
    i?86)   arch="x86"  ;;
    amd64)  arch="amd64"    ;;
    x86_64) arch="amd64"    ;;
    * ) echo "Your Arch '$arch' -> Its not supported."  ;;
esac

# Populate arrays based on the arch
case "$arch" in
    x86)
    ARRAYA+=('LITEWELCOME')
    ;;
    amd64)
    ARRAYA+=('LITEWELCOME')
    ;;
esac
}

LL52() {
# Invoke arrays
ARRAYA=()       # Array for LL 5.2

# check the arch
log_upgrade "Checking Architecture:"
arch=$(uname -m) ; log_upgrade "$arch"

case "$arch" in
    x86)    arch="x86"  ;;
    i?86)   arch="x86"  ;;
    amd64)  arch="amd64"    ;;
    x86_64) arch="amd64"    ;;
    * ) echo "Your Arch '$arch' -> Its not supported."  ;;
esac

# Populate arrays based on the arch
case "$arch" in
    x86)
    ARRAYA+=('LITEWELCOME')
    ;;
    amd64)
    ARRAYA+=('LITEWELCOME')
    ;;
esac
}

LL54() {
# Invoke arrays
ARRAYA=()       # Array for LL 5.4

# check the arch
log_upgrade "Checking Architecture:"
arch=$(uname -m) ; log_upgrade "$arch"

case "$arch" in
    x86)    arch="x86"  ;;
    i?86)   arch="x86"  ;;
    amd64)  arch="amd64"    ;;
    x86_64) arch="amd64"    ;;
    * ) echo "Your Arch '$arch' -> Its not supported."  ;;
esac

# Populate arrays based on the arch
case "$arch" in
    x86)
    ARRAYA+=('LITEWELCOME')
    ;;
    amd64)
    ARRAYA+=('LITEWELCOME')
    ;;
esac
}

LL56() {
# Invoke arrays
ARRAYA=()       # Array for LL 5.6

# check the arch
log_upgrade "Checking Architecture:"
arch=$(uname -m) ; log_upgrade "$arch"

case "$arch" in
    x86)    arch="x86"  ;;
    i?86)   arch="x86"  ;;
    amd64)  arch="amd64"    ;;
    x86_64) arch="amd64"    ;;
    * ) echo "Your Arch '$arch' -> Its not supported."  ;;
esac

# Populate arrays based on the arch
case "$arch" in
    x86)
    ARRAYA+=('LITEWELCOME')
    ;;
    amd64)
    ARRAYA+=('LITEWELCOME')
    ;;
esac
}

RUN() {
  log_upgrade "Executing upgrades..."
# Check if ARRAYA is empty - If it is empty skip the execution
if [ ${#ARRAYA[@]} -ne 0 ]; then
    x=0
    for k in "${!ARRAYA[@]}"; do  x=$(( $x + 1 )); done  # Get the total number of selected items in array A
    TOTAL_LINES=$x
    printf '%s \n' "${ARRAYA[@]}"|
    while read  line; do
      $line     # Execute functions one by one
      if [ $? = 1 ]; then log_upgrade "Error - $line"; zenity --error --width="300" --title="$APPNAME" --text="\nAn error occurred while performing upgrades:\n ${line}"; exit 1 ; fi
      let i++
        (( PERCENTAGE = 100 \* ${i} / ${TOTAL_LINES} ))
        echo "$PERCENTAGE"
        if [ "$PERCENTAGE" == "100" ]; then echo "#⚫ Completed." && sleep 2 ; fi
      done| zenity --progress  --title="$APPNAME" --auto-kill --auto-close --no-cancel --width=400
fi

export -f log_upgrade; export MYUSER REPORTERROR UPGR APPNAME LOGFILE IC
/usr/bin/lite-upgrade-system-series5     # Run the next script

if grep "Linux Lite ${UPGR}" /etc/llver; then log_upgrade "Upgrade succeeded."; REBOOT; else log_upgrade "Upgrade failed - /etc/llver is not ${UPGR}"; zenity --info --title="$APPNAME" --text="Upgrade canceled."; fi
}

upgrade_exec() {
# check LL current version and start the appropriate function
log_upgrade "Upgrading version:"
# check if version release exists in /etc/llver. If not, create it from /etc/issue file
if [ "$(grep -c "Linux Lite" /etc/llver)" -ge 1 ]; then :; else grep "Linux Lite" /etc/issue | cut -c 1-14 > /etc/llver; fi
# check LL version and start the appropriate function
if grep "Linux Lite 5.0" /etc/llver; then log_upgrade "Linux Lite 5.0"; LL50
elif grep "Linux Lite 5.2" /etc/llver; then log_upgrade "Linux Lite 5.2"; LL52
elif grep "Linux Lite 5.4" /etc/llver; then log_upgrade "Linux Lite 5.4"; LL54
elif grep "Linux Lite 5.6" /etc/llver; then log_upgrade "Linux Lite 5.6"; LL56
#elif grep "Linux Lite 5.8" /etc/llver; then log_upgrade "Linux Lite 5.8"; LL58
#else latest_version
else
	echo "nothing"
#	zenity --info --title="$APPNAME" --text="msg here"
fi
}

# We start here
latest_version() { if grep "Linux Lite 5.8" /etc/llver; then log_upgrade "Linux Lite $UPGR"; zenity --info --title="No need to Upgrade" --window-icon="$ic" --width="300" --text="\nYou are already running the latest release."; exit 0 ; else :; fi }
latest_version

# First dialog box - we must ask for elevation from the start otherwise a regular user can run lite-upgrade-series5 unnecessarily
if [ $EUID -ne 0 ]; then
  zenity --question --icon-name="info" --width="430" --title="$APPNAME" \
         --window-icon="$ic" --cancel-label="Cancel" --ok-label="Upgrade" \
         --text="\nYou are currently running: <b>$GETLLVER</b>\n
You are about to upgrade to: <b>$UPGRFULL</b>\n
Your computer must remain connected to the internet during this time.\n
A connectivity check to the Linux Lite repositories will be conducted to make sure that the connection with the server can be established.\n
Once upgrades have taken place, you must restart the system to complete the upgrade process. Please save and close your work <b>now</b> before continuing.\n\n
Click <b>Cancel</b> to exit now or <b>Upgrade</b> to proceed.\n"
# If No is clicked then exit
if [ "${PIPESTATUS[0]}" -ne "0" ]; then
log_upgrade "user canceled - main dialog"
exit 0
fi

case $? in
    0) log_upgrade "Checking Internet access..."
    if eval "curl -sk google.com" >> /dev/null 2>&1; then
      :; log_upgrade "Internet connection check passed!"
    else # Prompt ERROR internet connection check failed and exit
        zenity --info --width=320 --height=120 --ok-label="Close" --title="$APPNAME - Aborted" \
                --text="\n<b>Your computer is not connected to the internet</b> \n\n$APPNAME cannot continue. \nPlease check your Internet connection and try again."
            log_upgrade "the computer is not connected to the internet - $APPNAME aborted."
            exit 0
    fi
    log_upgrade "Checking connectivity to Master Repository..."
    curl -sk repo.linuxliteos.com/linuxlite/db/version
        if [ ${?} -ne 0 ]; then
          log_upgrade "Cannot connect to Linux Lite Master Repository - aborted"
          zenity --error --title="$APPNAME - Aborted" --width="320" --ok-label="Close" \
          --text="\nLinux Lite Upgrade Utility was unable to establish connection with the Linux Lite master repository.\n
Please check your internet connection and try again.\n\nUpgrade has been canceled."
          exit 0
        else
          log_upgrade "Linux Lite Master is ONLINE - passed."; :
        fi

        pkexec $0; if [ "${PIPESTATUS[@]}" -eq "126" ] || [ "${PIPESTATUS[@]}" -eq "127" ] ; then log_upgrade "Authentication canceled - aborted"; exit 0 ; fi ;;
    1) :;;
    esac
fi

test -e ["/var/log/lite-upgrade.log"] || rm -rf /var/log/lite-upgrade.log
test -e ["/tmp/lite-upgrade.log"] || rm -rf /tmp/lite-upgrade.log

upgrade_exec
RUN

exit 0
