#!/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.
	preferences[firstName]="$(inputbox "$(gettext "Please enter your first name.")" "${preferences[firstName]}")"
	preferences[lastName]="$(inputbox "$(gettext "Please enter your last name.")" "${preferences[lastName]}")"
	preferences[emailAddress]="$(inputbox "$(gettext "Please enter your email address.")" "${preferences[emailAddress]}")"
	# Username defaults to first name replacing spaces with dashes
	userName="${preferences[firstName],,}"
	userName="${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.")" "$userName")"
	# One last error guard for user name checking.
	if [[ -z "$userName" ]];then
		echo "username was blank, setting to default of f123" | log
		userName="f123"
	fi
	# 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

# Attempt to clear any system messages that may be spoken when Fenrir starts
counter=0
# Wait for the creation of the socket file. Break if it is not made after 10 seconds
while [[ ! -S /tmp/fenrirscreenreader-deamon.sock ]]; do
    sleep .25
    if [[ $counter -ge 40 ]]; then
        break
    fi
    ((counter++))
done
# Stop speech from previous output.
echo "command interrupt" | socat - UNIX-CLIENT:/tmp/fenrirscreenreader-deamon.sock |& log

# 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}"
if [[ "$keyboardLayout" != "nvda-desktop" ]]; then
    echo "Setting keyboard layout to $keyboardLayout" | log
    sudo sed -i "s/^keyboardLayout=.*/keyboardLayout=$keyboardLayout/" /etc/fenrirscreenreader/settings/settings.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 systemctl restart fenrirscreenreader |& log | dialog --progressbox "$(gettext "Applying Fenrir keyboard layout...") (${keyboardLayout})" 0 0
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 "Requesting user information." | log
get_user_info
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
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 "Please connect to the internet and try again."
	exit 1
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 "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
