#!/bin/bash
#
# Copyright 2018, F123 Consulting, <information@f123.org>
# Copyright 2018, Kyle, <kyle@free2.ml>
# Copyright 2018, Storm Dragon, <storm_dragon@linux-a11y.org>
#
# This is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free
# Software Foundation; either version 3, or (at your option) any later
# version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this package; see the file COPYING.  If not, write to the Free
# Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
#--code--

# the gettext essentials
export TEXTDOMAIN=update-f123light
export TEXTDOMAINDIR=/usr/share/locale

. gettext.sh

# Import the standard F123Light functions
. /usr/lib/F123-includes/script_functions.sh

cleanup() {
	# The temporary files downloaded from the F123Light git repositories are no longer needed.
	# Kill the clones.
	sudo -v && sudo rm -Rf /tmp/files-F123Light /tmp/content-F123Light
}

# Log writing function
log() {
	while read -r line ; do
		echo "$line" | sudo tee -a "$logFile" &> /dev/null
	done
}

# Incremental update timestamp function
# Determine whether to perform the update that calls this function.
# Return false if the time in yymmddhhmm format is not later than /etc/build-timestamp
# Otherwise write the new timestamp and return 0 so that the update is performed.
# on the calling system.
update () {
	local updateTime="$1"
	local lastUpdated="$(cat /etc/timestamp-f123light | tr -cd '[:digit:]' 2> /dev/null)"
	lastUpdated=${lastUpdated:-0}
	if [[ $updateTime -gt $lastUpdated ]]; then
		echo -n "$updateTime" | sudo tee /etc/timestamp-f123light &> /dev/null
		echo "Performed incremental update $updateTime" | log
	else
		return 100
    fi
	return 0
}

reboot_prompt () {
    # Prompt the user to reboot just in case something like the kernel that deserves a reboot has been updated.
    # We will prompt for a keypress. Enter to reboot, escape to exit the script and return to the shell or calling script.
    local $key
    clear
    key=$(yesno "$(gettext "Your system has been updated. We recommend that you restart your computer. Please press 'Enter' to restart or 'Escape' to finish the update without restarting.")")
        case $key in
            "Yes")
                sudo systemctl reboot
            ;;
            "No")
            ;;
        esac
}

# Default files-F123Light git branch to be cloned
branch=master

# test to determine whether to prompt for a reboot, initially false
reboot=false

# Get command line options
if ! options=$(getopt -o b:h -l branch:,help, -n "update-f123light" -- "$@"); then
	exit 1
fi

eval set -- "$options"

while [[ $# -gt 0 ]]; do
	case $1 in
		-b|--branch)
			branch="$2"
			shift 2
		;;
		-h|--help)
			cat <<-HELP
				$(gettext "Usage")
				$(eval_gettext "\$name [options...]")
				$(gettext "Options")
				-h, --help: $(gettext "Print this help message and exit")
				-b <branch>, --branch=<branch>: $(eval_gettext "Get files from the specified git branch, default: \$branch")
			HELP
			exit 0
		;;
		(--)
			shift
		;;
		*)
			echo $(basename $0): $1 $(gettext "not recognized") 1>&2
			exit 1
		;;
	esac
done

clear
set -Eo pipefail
trap cleanup EXIT
# Log file name
logFile="/var/log/${0##*/}"

# Check if the current user uas sudo privileges.
if sudo -v ; then
	# Initialize logFile.
	echo "Log for update-f123light. Starting at version $(</etc/timestamp-f123light)" | sudo tee "$logFile" &> /dev/null
else
	infobox "$USER $(gettext "Does not currently have administrator access to this system. Please upgrade with a user that has adminstrator access.")";
	exit 1;
fi

# See if we can update the system.
if [[ -f "/var/lib/pacman/db.lck" ]]; then
    echo "Found /var/lib/pacman/db.lck" | log
    if [[ "$(yesno "$(gettext "Your system needs to restart before updates can begin. Would you like to do this now?")")" == "Yes" ]]; then
        sudo rm -f "/var/lib/pacman/db.lck"
    echo "Removed /var/lib/pacman/db.lck" | log
        sudo reboot
    else
    echo "User chose not to remove /var/lib/pacman/db.lck" | log
        exit 0
    fi
fi

# Check for internet connectivity.
if ! ping -c1 -W5 f123.org &> /dev/null | dialog --progressbox "$(gettext "Checking internet connection...")" 0 0; then
	echo "Could not connect to internet" | log
	infobox "$(gettext "No internet connection detected. Please connect to the internet and try again.")"
	exit 1
fi

# Check for free space in /tmp
# Get free size on disk
freeSpace=$(df -h --output=avail /tmp | tr -Cd '[:digit:]')
if [[ $freeSpace -lt 50 ]]; then
	echo "Not enough free space on the disk to do updates." | log
    infobox "$(gettext "There is not enough free space on the disk to update the system.")"
	exit 1
fi

# Make sure update-f123light is up to date.
oldVersion="$(pacman -Qi update-f123light | head -2 | tail -1)"
sudo pacman -Sy --noconfirm --needed update-f123light &> /dev/null | dialog --progressbox "Checking to make sure you have the latest version of update-f123light" -1 -1
newVersion="$(pacman -Qi update-f123light | head -2 | tail -1)"
if [[ "$oldVersion" != "$newVersion" ]]; then
	echo "update-f123light was updated from version $oldVersion to $newVersion" | log
	msgbox "A new version of update-f123light has been installed. Please run update-f123light again."
	exit 0
fi

# Cleanup just in case there is a temporary file or content repository left behind from a previous update.
sudo rm -Rf /tmp/files-F123Light /tmp/content-F123Light

# Clone the files-F123Light and content-F123Light git repositories.
if git clone -q -b $branch --depth 1 https://gitlab.com/f123/files-F123Light.git /tmp/files-F123Light ; then
	echo "Cloned files-F123Light: $branch" | log
else
	echo "Failed to clone files-F123Light: $branch" | log
	infobox "$(gettext "Failed to download update files. Please try again later.")"
	exit 1
fi
if git clone -q --depth 1 https://gitlab.com/f123/content-F123Light.git /tmp/content-F123Light ; then
	echo "Cloned content-F123Light." | log
else
	echo "Failed to clone content-F123Light: $branch" | log
	msgbox "$(gettext "Failed to download content and language improvements. The update process will continue, but language improvements and documentation updates will not be added.")"
fi


# Due to the nature of system updates, this script may ask for the user's password more than once.
# Try to minimize user fears with a friendly message.
echo "All preupgrade checks passed." | log
msgbox "$(gettext "The software update process for F123Light will now begin. Depending on how many updates there are, your password might be requested more than once. Do not be alarmed, as this is normal. Press the 'Enter' key to continue, or the escape key to exit.")" || exit 0

# Perform incremental updates
# They are found in scripts/updates.sh in the files-F123Light repository
# This file explains how to apply incremental updates, usage, formatting, etc.
source /tmp/files-F123Light/scripts/updates.sh | dialog --progressbox "$(gettext "Performing incremental updates...")" -1 -1

# Clean the package cache.
sudo pacman -Sc --noconfirm |& log | dialog --progressbox "$(gettext "Cleaning package cache...")" -1 -1
if [[ $? -ne 0 ]]; then
	echo "There were problems cleaning the package cache." | log
fi
# Update all ALARM and F123 maintained packages on the system that are not in the ignore list on public.f123.org.
# Track kernel version and prompt for a reboot after if it changes
oldKernel="$(uname -r)"
oldKernel="${oldKernel%-*}"
ignorePkgList="$(curl -Ls public.f123.org/update-f123light/ignorepkg.txt)"
if [[ -n "${ignorePkgList}" ]]; then
    ignorePkgList="--ignore ${ignorePkgList//[[:space:]]/,} "
fi
yes | sudo pacman -Syu --noconfirm --noprogressbar ${ignorePkgList}|& sudo tee -a "$logFile" | grep -v '\? \[Y/n\]' | dialog --progressbox "$(gettext "Updating system software...")" -1 -1
newKernel="$(pacman -Qi linux-raspberrypi | head -2 | tail -1)"
newKernel="${newKernel##* }"
if [[ "$oldKernel" != "$newKernel" ]]; then
	reboot="true"
	echo "The kernel was upgraded from version ${oldKernel%%-*} to version ${newKernel%%-*}" | log
fi

infobox "$(gettext "Updating configuration and other files...")"

# Copy in the files-F123Light and content-F123Light files.
# Only the files under files-F123Light/files/usr should be copied to the system to avoid resetting configs modified by the system menu.
# Everything in content-F123Light is always copied.

shopt -s dotglob
sudo cp -a /tmp/files-F123Light/files/usr/* /usr
# Update F123Light specific configuration directory.
sudo cp -a /tmp/files-F123Light/files/etc/F123-Config/* /etc/F123-Config
# /boot is a special case on a Raspberry Pi, as it's an oldschool DOS partition.
if uname -m | grep -q armv7 ; then
    sudo cp -R /tmp/files-F123Light/files/boot/* /boot |& log
fi
sudo cp -R /tmp/content-F123Light/F123/* /usr/share/doc/F123


if [[ "$reboot" == "true" ]]; then
reboot_prompt
fi

msgbox "$(gettext "Update complete.")"

exit 0
