#!/usr/bin/env bash

trap cleanup EXIT
cleanup() {
    echo "Thank you for choosing Stormux!"
}

# Volume calibration is now handled in stormux_first_boot.sh

export DIALOGOPTS='--insecure --no-lines --visit-items'

set_timezone() {
    # Get the list of timezones
    mapfile -t regions < <(timedatectl --no-pager list-timezones | cut -d '/' -f1 | sort -u)

    # Use the same text twice here and just hide the tag field.
        region=$(dialog --backtitle "Please select your Region" \
                --no-tags \
                --menu "Use up and down arrows or page-up and page-down to navigate the list, and press 'Enter' to make your selection." 0 0 0 \
                $(for i in "${regions[@]}" ; do echo "$i";echo "$i";done) --stdout)


    mapfile -t cities < <(timedatectl --no-pager list-timezones | grep "$region" | cut -d '/' -f2 | sort -u)

    # Use the same text twice here and just hide the tag field.
        city=$(dialog --backtitle "Please select a city near you" \
                --no-tags \
                --menu "Use up and down arrow or page-up and page-down to navigate the list." 0 0 10 \
                $(for i in "${cities[@]}" ; do echo "$i";echo "$i";done) --stdout)

    # Set the timezone
    if [[ -f /etc/localtime ]]; then
        rm /etc/localtime
    fi
    ln -sf /usr/share/zoneinfo/"${region}"/"${city}" /etc/localtime
    timedatectl set-ntp true
}
# Offer to switch fenrir layout.
echo "Would you like to switch Fenrir to laptop layout?"
echo "Press y for yes or n for no followed by enter."
read -r continue
continue="${continue::1}"
if [[ "${continue,}" == "y" ]];then
    sed -i 's/=desktop/=laptop/' /etc/fenrirscreenreader/settings/settings.conf
    clear
    systemctl restart fenrirscreenreader.service
fi

if ! ping -c1 stormux.org &> /dev/null ; then
    echo "No internet connection detected. Press enter to open NetworkManager."
    read -r continue
    echo "setting set focus#highlight=True" | socat - UNIX-CLIENT:/tmp/fenrirscreenreader-deamon.sock
    nmtui-connect
    echo "setting set focus#highlight=False" | socat - UNIX-CLIENT:/tmp/fenrirscreenreader-deamon.sock
fi
# Check for internet connectivity
if ping -qc1 -W 1 stormux.org &> /dev/null; then
    echo "Updating the clock to prevent certificate errors..."
    # Get current date and time
    date_time=$(curl -s http://worldtimeapi.org/api/ip | grep -oP '(?<="datetime":")[^"]*')
    echo "Current date and time: $date_time"
    # set date and time
    date -s "$date_time"
    set_timezone
else
    echo "Please connect to the internet and run ${0##*/} again."
    exit 1
fi

echo
read -rp "Would you like to run the Stormux installer? [y/N]: " answer
answer="${answer:0:1}"
if [[ "${answer,,}" == "y" ]]; then
    install-stormux
else
    echo
    echo "To run the Stormux installer, type install-stormux"
    echo
    exit 0
fi
