#!/bin/bash
#----------------------------------------------------------------
# Description: Linux Lite Upgrade Script - Home
# About: For Linux Lite 4.- 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

# Release Upgrade
UPGR="4.8"
UPGRFULL="Linux Lite 4.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."
# delete previous lite-upgrade.log file & create a new one
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 ----------"

# Functions

# Create backup directories for Linux Lite 4.0
MKDIRBUPS40() {
  log_upgrade "MKDIRBUPS40"
  echo "#⚫ Creating backup directories..." && sleep 2
  (mkdir -p /home/$MYUSER/.llupgradebackup/4.0 ; chown -R $MYUSER:$MYUSER /home/$MYUSER/.llupgradebackup) 2>&1 | tee -a $LOGFILE
  if [ "${PIPESTATUS[0]}" -ne "0" ]; then echo "#✘ Error..." && sleep 2;
    zenity --error --width="320" --title="$APPNAME - Error" --text="An error occurred while creating backup directories.\n\n$REPORTERROR\nUpgrade canceled."; exit 1
  fi
}

# Create backup directories for Linux Lite 4.2
MKDIRBUPS42() {
  log_upgrade "MKDIRBUPS42"
  echo "#⚫ Creating backup directories..." && sleep 2
  (mkdir -p /home/$MYUSER/.llupgradebackup/4.2 ; chown -R $MYUSER:$MYUSER /home/$MYUSER/.llupgradebackup) 2>&1 | tee -a $LOGFILE
  if [ "${PIPESTATUS[0]}" -ne "0" ]; then echo "#✘ Error..." && sleep 2;
    zenity --error --width="320" --title="$APPNAME - Error" --text="An error occurred while creating backup directories.\n\n$REPORTERROR\nUpgrade canceled."; exit 1
  fi
}

# Create backup directories for Linux Lite 4.4
MKDIRBUPS44() {
  log_upgrade "MKDIRBUPS44"
  echo "#⚫ Creating backup directories..." && sleep 2
  (mkdir -p /home/$MYUSER/.llupgradebackup/4.4 ; chown -R $MYUSER:$MYUSER /home/$MYUSER/.llupgradebackup) 2>&1 | tee -a $LOGFILE
  if [ "${PIPESTATUS[0]}" -ne "0" ]; then echo "#✘ Error..." && sleep 2;
    zenity --error --width="320" --title="$APPNAME - Error" --text="An error occurred while creating backup directories.\n\n$REPORTERROR\nUpgrade canceled."; exit 1
  fi
}

# Create backup directories for Linux Lite 4.6
MKDIRBUPS46() {
  log_upgrade "MKDIRBUPS46"
  echo "#⚫ Creating backup directories..." && sleep 2
  (mkdir -p /home/$MYUSER/.llupgradebackup/4.6 ; chown -R $MYUSER:$MYUSER /home/$MYUSER/.llupgradebackup) 2>&1 | tee -a $LOGFILE
  if [ "${PIPESTATUS[0]}" -ne "0" ]; then echo "#✘ Error..." && sleep 2;
    zenity --error --width="320" --title="$APPNAME - Error" --text="An error occurred while creating backup directories.\n\n$REPORTERROR\nUpgrade canceled."; exit 1
  fi
}

# BACK UP HOME FILES HERE


# FIRST LOCAL MODIFICATION HERE


# Set lite-welcome to autostart on first boot
LITEWELCOME() {
  log_upgrade "LITEWELCOME"
  echo "#⚫ Setting Lite Welcome to autostart..." && sleep 2
  if [ ! -f /home/$MYUSER/.config/autostart/lite-welcome.desktop ]; then
  UPDATER=$( ln -s /usr/share/applications/lite-welcome.desktop /home/$MYUSER/.config/autostart 2>&1 | tee -a $LOGFILE )
  else :; fi
unset UPDATER
}

REBOOT() {
  log_upgrade "Waiting for restart confirmation..." && log_upgrade "Moving upgrade log to user's home directory... All done."
    mv -f "$LOGFILE" /home/$MYUSER/ ; chown $MYUSER:$MYUSER "$LOGFILE"
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}/apps/32/system-reboot.png" ]; then APPICON="/usr/share/icons/${THEME}"
  else APPICON="/usr/share/icons/Papirus"
  fi
  title="$APPNAME"
  exit_type=$(zenity --width="380" --height="230" --window-icon="$ic" --cancel-label="Continue without restart" --title="$title" --text='                <span font="Sans Bold 10">Upgrade routine completed</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")

  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
    dbus-send --system --print-reply --dest="org.freedesktop.ConsoleKit" /org/freedesktop/ConsoleKit/Manager org.freedesktop.ConsoleKit.Manager.Restart
  elif [ "$exit_type" = "Shutdown" ]; then
      dbus-send --system --print-reply --dest="org.freedesktop.ConsoleKit" /org/freedesktop/ConsoleKit/Manager org.freedesktop.ConsoleKit.Manager.Stop
  else zenity --info --width="300" --timeout="2" --ok-label="Back" --title="$APPNAME" --text="\nPlease choose one of the available options."; continue
  fi
  done
}

LL40() {
# Invoke arrays
ARRAYA=()       # Array for LL 4.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+=('MKDIRBUPS40')
    ARRAYA+=('LITEWELCOME')
    ;;
    amd64)
    ARRAYA+=('MKDIRBUPS40')
    ARRAYA+=('LITEWELCOME')
    ;;
esac
}

LL42() {
# Invoke arrays
ARRAYA=()       # Array for LL 4.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+=('MKDIRBUPS42')
    ARRAYA+=('LITEWELCOME')
    ;;
    amd64)
    ARRAYA+=('MKDIRBUPS42')
    ARRAYA+=('LITEWELCOME')
    ;;
esac
}

LL44() {
# Invoke arrays
ARRAYA=()       # Array for LL 4.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+=('MKDIRBUPS44')
    ARRAYA+=('LITEWELCOME')
    ;;
    amd64)
    ARRAYA+=('MKDIRBUPS44')
    ARRAYA+=('LITEWELCOME')
    ;;
esac
}

LL46() {
# Invoke arrays
ARRAYA=()       # Array for LL 4.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+=('MKDIRBUPS46')
    ARRAYA+=('LITEWELCOME')
    ;;
    amd64)
    ARRAYA+=('MKDIRBUPS46')
    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-series4     # 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 4.0" /etc/llver; then log_upgrade "Linux Lite 4.0"; LL40
elif grep "Linux Lite 4.2" /etc/llver; then log_upgrade "Linux Lite 4.2"; LL42
elif grep "Linux Lite 4.4" /etc/llver; then log_upgrade "Linux Lite 4.4"; LL44
elif grep "Linux Lite 4.6" /etc/llver; then log_upgrade "Linux Lite 4.6"; LL46
elif grep "Linux Lite 4.8" /etc/llver; then log_upgrade "Linux Lite 4.8"; LL48
else latest_version
fi
}

# We start here
latest_version() { if grep "Linux Lite 4.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-series4 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
        gksu -m '
    <b>   Lite Upgrade requires Administrative privileges</b>

     Please enter your password to continue.'  $0; exit 0 ; if [ "${PIPESTATUS[@]}" -eq "255" ]; then log_upgrade "Authentication canceled - aborted"; exit 0 ; fi ;;
    1) :;;
    esac
fi

upgrade_exec
RUN

exit 0
