#!/bin/bash
set -euo pipefail
##################################################################################################################
# Author    : Erik Dubois
# Website   : https://www.erikdubois.be
# Website   : https://www.alci.online
# Website   : https://www.arcolinux.info
# Website   : https://www.arcolinux.com
# Website   : https://www.arcolinuxd.com
# Website   : https://www.arcolinuxb.com
# Website   : https://www.arcolinuxiso.com
# Website   : https://www.arcolinuxforum.com
##################################################################################################################
#
#   DO NOT JUST RUN THIS. EXAMINE AND JUDGE. RUN AT YOUR OWN RISK.
#
##################################################################################################################
#tput setaf 0 = black 
#tput setaf 1 = red 
#tput setaf 2 = green
#tput setaf 3 = yellow 
#tput setaf 4 = dark blue 
#tput setaf 5 = purple
#tput setaf 6 = cyan 
#tput setaf 7 = gray 
#tput setaf 8 = light blue
##################################################################################################################

# Constants
REMOTE_URL="https://raw.githubusercontent.com/arcolinux/arcolinux-mirrorlist/refs/heads/master/etc/pacman.d/arcolinux-mirrorlist"
LOCAL_MIRRORLIST="/usr/local/share/arcolinux/pacman.d/arcolinux-mirrorlist"
DEST_MIRRORLIST="/etc/pacman.d/arcolinux-mirrorlist"

# Check dependencies
command -v wget > /dev/null || { echo "wget is required but not installed. Aborting."; exit 1; }

check_connectivity() {
    if ping -c1 8.8.8.8 > /dev/null 2>&1; then
        echo "You have internet connectivity"
        return 0
    else
        echo "You do not have connectivity"
        return 1
    fi
}

check_local_file() {
    local file="$LOCAL_MIRRORLIST"
    if [[ -f "$file" ]]; then
        echo "$file exists"
        return 0
    else
        echo "$file doesn't exist"
        return 1
    fi
}

main() {
    echo "###############################################################################"
    echo "Getting latest /etc/pacman.d/arcolinux-mirrors"
    echo "###############################################################################"

    if check_connectivity; then
        echo "Fetching latest mirror list from GitHub..."
        sudo wget "$REMOTE_URL" -O "$DEST_MIRRORLIST"
    elif check_local_file; then
        echo "Offline: Copying local mirror list..."
        sudo cp "$LOCAL_MIRRORLIST" "$DEST_MIRRORLIST"
    else
        echo "Run this script once you are back online and/or ensure the local file exists."
        exit 1
    fi

    echo "###############################################################################"
    echo "###                DONE - YOU CAN CLOSE THIS WINDOW                        ####"
    echo "###############################################################################"
}

main
