#!/bin/bash
declare -a arr=("mirror.nl.foxcloud.net" "mirror.us.foxcloud.net" "mirror.ru.foxcloud.net" "mirror.md.foxcloud.net")

MIRROR=""
BESTPING=1000

for m in "${arr[@]}"
do
    echo "Testing $m"
    val=`ping -c 3 $m -q -w 1 -i 0.5 | tail -1 | awk '{print $4}' | cut -d '.' -f 1`
    echo "ping: $val"
    if [ "$val" -lt "$BESTPING" ]; then
        BESTPING=$val
        MIRROR=$m
    fi
done

echo "best mirror: $MIRROR ping: $BESTPING"

if cat /etc/*elea* | grep -q -i "centos linux release 8"; then
    wget -q -O /etc/yum.repos.d/foxcloud.repo https://$MIRROR/etc/centos/8/$MIRROR/foxcloud.repo
    if [ "$1" = "update" ]; then yum -y update; fi
elif cat /etc/*elea* | grep -q -i "centos linux release 7"; then
    wget -q -O /etc/yum.repos.d/foxcloud.repo https://$MIRROR/etc/centos/7/$MIRROR/foxcloud.repo
    if [ "$1" = "update" ]; then yum -y update; fi
elif cat /etc/*elea* | grep -q -i "ubuntu 18"; then
    wget -q -O /etc/apt/sources.list https://$MIRROR/etc/ubuntu/18/$MIRROR/sources.list
    export DEBIAN_FRONTEND=noninteractive
    apt-get -y update
    if [ "$1" = "update" ]; then apt-get upgrade -q -y; fi
elif cat /etc/*elea* | grep -q -i "ubuntu 20"; then
    wget -q -O /etc/apt/sources.list https://$MIRROR/etc/ubuntu/20/$MIRROR/sources.list
    export DEBIAN_FRONTEND=noninteractive
    apt-get -y update
    if [ "$1" = "update" ]; then apt-get upgrade -q -y; fi
elif cat /etc/*elea* | grep -q -i "Debian GNU/Linux 9"; then
    wget -q -O /etc/apt/sources.list https://$MIRROR/etc/debian/9/$MIRROR/sources.list
    export DEBIAN_FRONTEND=noninteractive
    apt-get -y update
    if [ "$1" = "update" ]; then apt-get upgrade -q -y; fi
elif cat /etc/*elea* | grep -q -i "Debian GNU/Linux 10"; then
    wget -q -O /etc/apt/sources.list https://$MIRROR/etc/debian/10/$MIRROR/sources.list
    export DEBIAN_FRONTEND=noninteractive
    apt-get -y update
    if [ "$1" = "update" ]; then apt-get upgrade -q -y; fi
fi
