#!/bin/bash
# FirstBoot
# A few preliminary steps that a user must take when boothing a new system for the first time
#
# 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--

# Setup gettext
export TEXTDOMAIN=first-boot
export TEXTDOMAINDIR=/usr/share/locale
. gettext.sh

# Include F123-includes
for i in /usr/lib/F123-includes/*.sh ; do
    source $i
done
source ~/.preferences

# Log writing function
log() {
    while read -r line ; do
        echo "$line" | sudo tee -a "$logFile" &> /dev/null
    done
}
 
# Log file name is /var/log/scriptname
logFile="/var/log/${0##*/}"
# Clear previous logs
echo -n | sudo tee "$logFile" &> /dev/null


get_user_info() {
    # Request first and last name.
    if [[ -z "${preferences[firstName]}" ]]; then
        preferences[firstName]="$(inputbox "$(gettext "Please enter your first name.")")"
    else
        previousValue="${preferences[firstName]}"
        preferences[firstName]="$(inputbox "$(gettext "Please enter your first name. Just press enter if your first name is:") ${preferences[firstName]}")"
        preferences[firstName]="${preferences[firstName]:-$previousValue}"
    fi
    if [[ -z "${preferences[lastName]}" ]]; then
        preferences[lastName]="$(inputbox "$(gettext "Please enter your last name.")")"
    else
        previousValue="${preferences[lastName]}"
        preferences[lastName]="$(inputbox "$(gettext "Please enter your last name. Just press enter if your last name is:") ${preferences[lastName]}")"
        preferences[lastName]="${preferences[lastName]:-$previousValue}"
    fi
    if [[ -z "${preferences[emailAddress]}" ]]; then
        preferences[emailAddress]="$(inputbox "$(gettext "Please enter your email address.")")"
    else
        previousValue="${preferences[emailAddress]}"
        preferences[emailAddress]="$(inputbox "$(gettext "Please enter your email address. Just press enter if your email address is:") ${preferences[emailAddress]}")"
        preferences[emailAddress]="${preferences[emailAddress]:-$previousValue}"
    fi
	# Username defaults to first name replacing spaces with dashes
	userName="${preferences[firstName],,}"
	userName="${userName//[[:punct:][:space:]]/-}"
	# Make sure username has a value.
	userName="${userName:-f123}"
	previousValue="${userName}"
	userName="$(inputbox "$(gettext "Please enter your username for this computer. Usernames are usually lower case and contain only letters, numbers, and dashes. The name must not start with a dash. Please note, if you set a password earlier it will be the password for the new username, otherwise the password will be f123. Just press enter if you want your username to be:") $userName")"
	userName="${userName:-$previousValue}"
	# Write the name and email stuff to preferences file
	write_preferences
}

get_internet() {
    # Initial connection to wifi
    # Args: none
    # Returns: none
    fold -sw$cols <<-EOF
	$(gettext "In order to use the internet, you need to set up a network connection.
	If you already plugged in a wire that is connected directly to a router or modem, you don't need to do anything here.
	However, if you don't have a wire connected, but want to use the internet, you can configure the wireless network here.")
EOF
    while true; do
        #echo -n "$(gettext "Press enter to configure the wireless network, or escape to skip this step. ")"
        key="$(yesno "$(gettext "Would you like to configure the wireless network now? An internet connection is required to continue setup.")")"
        echo
        case "$key" in
            "Yes")
                sudo configure-wifi
                break
            ;;
            "No")
                break
            ;;
        esac
    done
}

setup_complete() {
	# Final comments
	# Args: none
	# Returns: none
	msgbox "$(gettext "Initial F123 Light configuration is complete. To further customize your computer, please use the settings menu. Your computer will now reboot to finalize the setup.")"
	# remove the firstboot file if it exists.
	[[ -e ~/.firstboot ]] && rm -fv ~/.firstboot |& log
	if [[ "$userName" != "f123" && "$userName" != "$USER" ]]; then
		/usr/lib/F123-wrappers/chuser.sh $userName
	fi
	sudo reboot
}

set -o pipefail

# Make sure the soundcard is not muted.
if amixer get Master | grep -q '\[off\]' ; then
    amixer sset Master unmute |& log
fi
# Check system volume, try to make sure it is unmuted and at a reasonable level.
soundcardVolume=$(amixer get Master | grep '\[on\]' | cut -d '['  -f2 | cut -d '%' -f1 | head -1)
if [[ $soundcardVolume -le 25 ]]; then
    amixer sset Master 50% |& log
fi

# Make sure basic xdg directory structure is in place:
xdg-user-dirs-update |& log

# Add any user based systemd service files here. remember to pipe output through the log function.
systemctl --user enable --now recoll.service |& log

# Call the functions that make up this script.
# I tried to make the functions descriptive as to what they do.
# See comments in the functions themselves for details
if [[ ! -s ~/.firstboot ]]; then
	touch ~/.firstboot
	echo "Running /usr/lib/F123-wrappers/select-language.sh" | log
	/usr/lib/F123-wrappers/select-language.sh
fi

# Start keyboard layout.
msgbox "$(gettext "The Fenrir screenreader has several keyboard layouts available. On the next screen, you will be ask to choose the keyboard layout with which you are most familiar. To accept the default, NVDA Desktop layout, simply press enter.")"
declare -a keyboardMenu=("nvda-desktop" "nvda-desktop-default")
for i in $(find /etc/fenrirscreenreader/keyboard -type f -name '*.conf' -not -iname 'pty*') ; do
    i="${i##*/}"
    i="${i%.conf}"
    keyboardMenu+=("${i}" "${i}")
done
keyboardLayout="$(menulist ${keyboardMenu[@]})"
keyboardLayout="${keyboardLayout:-nvda-desktop}"
keyboardLayout="${keyboardLayout/nvda-desktop-default/nvda-desktop}"
if ! grep -q "^keyboardLayout=$keyboardLayout" /etc/fenrirscreenreader/settings/settings.conf ; then
    echo "Setting keyboard layout to $keyboardLayout" | log
    sudo sed -i "s/^keyboardLayout=.*/keyboardLayout=$keyboardLayout/" /etc/fenrirscreenreader/settings/settings.conf /etc/fenrirscreenreader/settings/xterm.conf |& log
    echo "Backing up Fenrir Settings." | log
    sudo sudo cp -v /etc/fenrirscreenreader/settings/settings.conf /etc/F123-Config/backup/fenrir.conf |& log
    sudo sudo cp -v /etc/fenrirscreenreader/settings/xterm.conf /etc/F123-Config/backup/xterm.conf |& log
    msgbox "$(gettext "Your Fenrir keyboard configuration will be applied at the conclusion of the first-boot process.")"
fi
# End keyboard layout

# Show quick start
if [[ -f "/usr/share/doc/F123/${LANG}/quickstart.txt" ]]; then
	echo "Displaying /usr/share/doc/F123/${LANG}/quickstart.txt" | log
	show_doc "/usr/share/doc/F123/${LANG}/quickstart.txt"
else
	echo "No quickstart for ${LANG}, displaying default /usr/share/doc/F123/en_US.UTF-8/quickstart.txt" | log
	show_doc "/usr/share/doc/F123/en_US.UTF-8/quickstart.txt"
fi
echo "Prompting for password change." | log
if [[ "$(yesno "$(gettext "Do you want to change passwords for users of this system? Since everyone knows that the default password is f123, it is recommended that you change it.")")" == "Yes" ]]; then
	echo "Running /usr/lib/F123-wrappers/configure-passwords.sh" | log
	/usr/lib/F123-wrappers/configure-passwords.sh
fi
echo "Requesting user information." | log
get_user_info
if ! ping -c1 gitlab.com |& log | dialog --progressbox "$(gettext "Checking internet connection...")" 0 0 ; then
	echo "prompting for internet connectivity information." | log
	get_internet
fi
# Check for internet connectivity.
if ! ping -c1 gitlab.com |& log | dialog --progressbox "$(gettext "Checking internet connection...")" 0 0 ; then
	echo "Unable to establish an internet connection." | log
	gettext "Unable to connect to the internet. You may experience loss of functionality until a connection is established."
fi
# Set and sync timezone
echo "Running /usr/lib/F123-wrappers/timezone.sh" | log
/usr/lib/F123-wrappers/timezone.sh
# Synchronize repositories so that installations should go smoothly.
sudo pacman -Syy |& log | dialog --progressbox "$(gettext "Configuring system, please wait...")" 0 0
echo "Prompting for security configuration." | log
if [[ "$(yesno "$(gettext "Do you want to change security options for this system? If you press 'Enter' for yes, you will be able to make this computer a bit more secure, but also a bit less convenient.")")" == "Yes" ]]; then
	echo "Running /usr/lib/F123-wrappers/configure-security.sh" | log
	/usr/lib/F123-wrappers/configure-security.sh
fi
echo "displaying setup complete text" | log
setup_complete

exit 0
