#!/bin/bash

check_speed_and_download() {
    URL="$1"
    FILE="$2"

    echo "---------------------------------------------"
    echo "Downloading: $FILE"
    echo "URL: $URL"
    echo "---------------------------------------------"

    while true; do
        # Run wget and capture the speed
        OUTPUT=$(wget -cO "$FILE" --user-agent="Mozilla" "$URL" 2>&1)
        SPEED=$(echo "$OUTPUT" | grep -oP '[0-9.]+[KM]B/s' | tail -1)

        # If no speed detected, retry
        if [[ -z "$SPEED" ]]; then
            echo "No speed detected → retrying in 3 seconds..."
            sleep 3
            continue
        fi

        NUM=$(echo $SPEED | grep -oP '[0-9.]+' )
        UNIT=$(echo $SPEED | grep -oP '[KM](?=B/s)' )

        echo "Current speed: $SPEED"

        # Convert MB to KB
        if [[ "$UNIT" == "M" ]]; then
            NUM_KB=$(echo "$NUM * 1024" | bc)
        else
            NUM_KB="$NUM"
        fi

        # Round
        COMPARE=$(printf "%.0f" "$NUM_KB")

        # Check < 1000 KB/s
        if [[ "$COMPARE" -lt 1000 ]]; then
            echo "❌ Speed below 1MB/s ($SPEED) → retrying in 3 seconds..."
            sleep 3
            continue
        fi

        echo "✔ Completed download: $FILE"
        break
    done
}

# Download episodes
check_speed_and_download "http://flixpulse.top:2095/series/6783688736/5675856462/303986.mp4" "S01E134.mp4"
check_speed_and_download "http://flixpulse.top:2095/series/6783688736/5675856462/304579.mp4" "S01E135.mp4"
check_speed_and_download "http://flixpulse.top:2095/series/6783688736/5675856462/305286.mp4" "S01E136.mp4"
check_speed_and_download "http://flixpulse.top:2095/series/6783688736/5675856462/305618.mp4" "S01E137.mp4"
check_speed_and_download "http://flixpulse.top:2095/series/6783688736/5675856462/306227.mp4" "S01E138.mp4"
check_speed_and_download "http://flixpulse.top:2095/series/6783688736/5675856462/306437.mp4" "S01E139.mp4"
check_speed_and_download "http://flixpulse.top:2095/series/6783688736/5675856462/306437.mp4" "S01E140.mp4"

