#!/usr/bin/env bash

set -euo pipefail

ask_question() {
    local prompt="$1"
    local default_answer="$2"
    local answer

    while true; do
        echo -e "$prompt (y/n) [default: $default_answer]: \c"
        read -r answer
        answer="${answer:-$default_answer}"
        case "$answer" in
        [Yy]* ) return 0 ;;
        [Nn]* ) return 1 ;;
        * ) echo "Please answer yes or no." ;;
        esac
    done
}

has_internet() {
    if wget --header="x-garuda: garuda-diag-1" -q --spider https://garudalinux.org; then
        return 0
    else
        return 1
    fi
}

check_internet() {
    for i in {1..5}; do
        echo -e "\033[1;33m-->\033[1;34m Checking internet connection (Attempt $i of 5)...\033[0m"
        if has_internet; then
            return 0
        fi
        sleep 5
    done
    return 1
}

internet_setup() {
    if ! has_internet; then
        echo -e "\033[1;31mNo internet connection available.\033[0m"
        if ask_question "\033[1;34mI can try to help you set up a connection. Do you want to proceed?\033[0m" "Y"; then
            echo -e "\033[1;34mStarting NetworkManager...\033[0m"
            sudo systemctl start NetworkManager || true

            if check_internet; then
                echo -e "\033[1;32mInternet connection established!\033[0m"
                return
            else
                echo -e "\033[1;31mFailed to establish an internet connection automatically.\033[0m"
                if ask_question "\033[1;34mDo you want to open nmtui to set up a connection?\033[0m" "Y"; then
                    nmtui || true
                    if check_internet; then
                        echo -e "\033[1;32mInternet connection established!\033[0m"
                        return
                    fi
                fi
            fi
        fi

        echo -e "\033[1;31mNo internet connection available.\033[0m"
        echo -e "\033[1;31mCannot proceed without an internet connection. Exiting.\033[0m"
        exit 1
    fi
}

echo -e "\n\033[1;33m-->\033[1;34m Checking if internet connection is available...\033[0m"
internet_setup

ONLINE_FILE="https://garudalinux.org/os/garuda-diag/diagnostic"

echo -e "\n\033[1;35mThis utility will blindly execute the following script in a shell:\033[0m"
echo "$ONLINE_FILE"
echo -e "\033[1;34mYou can view the script in your web browser before proceeding.\033[0m"
echo -e "\033[1;34mThe script is downloaded from the internet to ensure the most up-to-date and relevant information is collected.\033[0m"

if ! ask_question "\033[1;34mDo you want to proceed?\033[0m" "Y"; then
    echo -e "\033[1;31mAborting...\033[0m"
    exit 1
fi

exec bash -c "VERSION=1 . <(wget -qO- '${ONLINE_FILE}') \"\$@\"" diagnostics "${@}"
