#!/bin/bash
TMP_DIR="/var/tmp/ncv4"
TMP_FILE="$TMP_DIR/check.tmp"
mkdir -p "$TMP_DIR"
ploss=100
max=0
avg=0
echo "0" > "$TMP_FILE"

echo "Network check is in progress. Don't close this window..."
echo $(date '+%d/%m/%Y %H:%M')


printf "+----------------------+----------+----------+----------+\n"
printf "| %-20s | %-8s | %-8s | %-8s |\n" "Host" "Loss" "Max" "Avg"
printf "+----------------------+----------+----------+----------+\n"


hoststate() {
    local hostname="$1"
    local host_file="$TMP_DIR/$hostname.hst"
    
    if [ ! -f "$host_file" ]; then
        printf "| %-20s | %-8s | %-8s | %-8s |\n" "$hostname" "File Error" "N/A" "N/A"
        printf "+----------------------+----------+----------+-----------------+\n"
        return
    fi
    
    ploss=$(grep -o '[0-9]\{1,3\}%' "$host_file" | tail -1 | tr -d '%')
    rtt_line=$(grep 'round-trip' "$host_file" | awk -F' = ' '{print $2}')
    
    if [[ -z "$rtt_line" ]]; then
        max="N/A"
        avg="N/A"
    else
        avg=$(echo $rtt_line | awk -F'/' '{print $2}')
        max=$(echo $rtt_line | awk -F'/' '{print $3}')
    fi
    
    if [[ -z "$ploss" ]]; then
        ploss=0
    fi
    
    printf "| %-20s | %-8s | %-8sms | %-8sms |\n" "$hostname" "${ploss}%" "${max}" "${avg}"
    printf "+----------------------+----------+------------+------------+\n"
}

#tut propisani hosts
HOSTS=(
    "google 8.8.8.8"
    "ovpn-main-1 ovpn-main-1.cola9.com"
    "ovpn-main-2 ovpn-main-2.cola9.com"
    "ovpn-main-3 ovpn-main-3.cola9.com"
    "ovpn-main-4 ovpn-main-4.cola9.com"
    "ovpn-main-5 ovpn-main-5.cola9.com"
    "ovpn-main-6 ovpn-main-6.cola9.com"
    "ovpn-main-7 ovpn-main-7.cola9.com"
    "2-vt 2-vt.cola9.com"
    "3-vt 3-vt.cola9.com"
    "4-vt 4-vt.cola9.com"
    "5-vt 5-vt.cola9.com"
)


for entry in "${HOSTS[@]}"; do
    hostname=$(echo $entry | awk '{print $1}')
    host=$(echo $entry | awk '{print $2}')
    packets=100  # тут можна змінити кількість пінгів
    cat << EOF > "$TMP_DIR/$hostname.sh"
#!/bin/bash
ping -c $packets $host > "$TMP_DIR/$hostname.hst"
EOF
    chmod +x "$TMP_DIR/$hostname.sh"
done


for script in "$TMP_DIR"/*.sh; do
    "$script" &
done

wait


for host_file in "$TMP_DIR"/*.hst; do
    hostname=$(basename "$host_file" .hst)
    hoststate "$hostname"
done

echo $(date '+%d/%m/%Y %H:%M')

# Clean up
rm -rf "$TMP_DIR"

read -n 1 -s -r -p "Press any key to exit"
echo " "
