#!/bin/bash

user_in_wheel_group=0

for group in $(groups)
do
    if [ "${group}" == "wheel" ]; then
        echo "Running..."

        user_in_wheel_group=1
        directory=$(mktemp -d --suffix=-mirrorlists)

        rate-mirrors --save "$directory/mirrorlist" --disable-comments-in-file arch
        rate-mirrors --save "$directory/cachyos-mirrorlist" --disable-comments-in-file /cachyos
        rate-mirrors --save "$directory/chaotic-mirrorlist" --disable-comments-in-file chaotic-aur
        rate-mirrors --save "$directory/endeavouros-mirrorlist" --disable-comments-in-file endeavouros

        find "$directory/" -mindepth 1 -maxdepth 1 -type f -name "*mirrorlist" -exec sudo cp -f {} /etc/pacman.d/ \;

        break
    fi
done

if [[ $user_in_wheel_group -eq 0 ]]; then
    echo "The user '${USER}' does not have permission to run this program."
    echo "The user '${USER}' is not a member of the 'wheel' or 'root' group."
    echo "Add user '${USER}' to the 'wheel' group, relogin and run again."
fi

echo "Finish!"

echo "This window may close!"

sleep 5