#!/bin/bash

# Settings
TMP_DIR="/var/tmp/ncv4"
TMP_FILE="$TMP_DIR/check.tmp"

# Create temporary directory if it doesn't exist
mkdir -p "$TMP_DIR"

# Reset variables
ploss=100
max=0
avg=0
echo "0" > "$TMP_FILE"

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

# Print table header with grid
printf "+----------------------+----------+----------+----------+\n"
printf "| %-20s | %-8s | %-8s | %-8s |\n" "Host" "Loss" "Max" "Avg"
printf "+----------------------+----------+----------+----------+\n"

# Function to check the state of the host
function hoststate {
    local hostname="$1"
    local host_file="$TMP_DIR/$hostname.hst"
    
    cat "$host_file" > "$TMP_FILE"
    
    if grep -q "Unknown host" "$TMP_FILE"; then
        printf "| %-20s | %-8s | %-8s | %-8s |\n" "$hostname" "DNS error" "N/A" "N/A"
        printf "+----------------------+----------+----------+----------+\n"
        return
    fi
    
    if grep -q "Destination host unreachable" "$TMP_FILE"; then
        printf "| %-20s | %-8s | %-8s | %-8s |\n" "$hostname" "DOWN" "N/A" "N/A"
        printf "+----------------------+----------+----------+----------+\n"
        return
    fi
    
    ploss=$(grep -oP '\d+(?=% packet loss)' "$TMP_FILE")
    rtt_line=$(grep 'rtt min/avg/max/mdev' "$TMP_FILE")
    max=$(echo $rtt_line | awk -F'/' '{print $6}')
    avg=$(echo $rtt_line | awk -F'/' '{print $5}')
    
    if [[ -z "$ploss" ]]; then
        ploss=0
    fi
    
    printf "| %-20s | %-8s | %-8s | %-8s |\n" "$hostname" "${ploss}%" "${max}ms" "${avg}ms"
    printf "+----------------------+----------+----------+----------+\n"
}

# List of hosts to check
declare -A 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"
)

# Create ping scripts
for hostname in "${!HOSTS[@]}"; do
    host="${HOSTS[$hostname]}"
    packets=100
    cat << EOF > "$TMP_DIR/$hostname.sh"
#!/bin/bash
ping -c $packets $host > "$TMP_DIR/$hostname.hst"
echo 'done' >> "$TMP_DIR/$hostname.hst"
EOF
    chmod +x "$TMP_DIR/$hostname.sh"
done

# Start multiple ping threads
for script in "$TMP_DIR"/*.sh; do
    "$script" &
done

wait

# Check the results
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 " "

