#!/bin/bash

# Fast Aria2 Download Script
# Usage: ./aria2-download.sh <URL> [output-filename]

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Check if aria2c is installed
if ! command -v aria2c &> /dev/null; then
    echo -e "${RED}aria2c is not installed!${NC}"
    echo "Installing aria2..."
    
    if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        if command -v apt-get &> /dev/null; then
            sudo apt-get update && sudo apt-get install -y aria2
        elif command -v yum &> /dev/null; then
            sudo yum install -y aria2
        elif command -v pacman &> /dev/null; then
            sudo pacman -S aria2
        else
            echo -e "${RED}Please install aria2 manually${NC}"
            exit 1
        fi
    elif [[ "$OSTYPE" == "darwin"* ]]; then
        if command -v brew &> /dev/null; then
            brew install aria2
        else
            echo -e "${RED}Please install Homebrew or aria2 manually${NC}"
            exit 1
        fi
    else
        echo -e "${RED}Unsupported OS. Please install aria2 manually${NC}"
        exit 1
    fi
fi

# Check if URL is provided
if [ -z "$1" ]; then
    echo -e "${RED}Error: No URL provided${NC}"
    echo "Usage: $0 <URL> [output-filename]"
    exit 1
fi

URL="$1"
OUTPUT_FILE="$2"

# Build aria2c command with optimized settings
ARIA2_CMD="aria2c \
    --max-connection-per-server=16 \
    --split=16 \
    --min-split-size=1M \
    --max-concurrent-downloads=16 \
    --continue=true \
    --max-tries=5 \
    --retry-wait=3 \
    --timeout=60 \
    --connect-timeout=30 \
    --file-allocation=none \
    --summary-interval=0 \
    --console-log-level=notice"

# Add output filename if provided
if [ -n "$OUTPUT_FILE" ]; then
    ARIA2_CMD="$ARIA2_CMD --out=\"$OUTPUT_FILE\""
fi

# Add URL
ARIA2_CMD="$ARIA2_CMD \"$URL\""

echo -e "${GREEN}Starting download...${NC}"
echo -e "${YELLOW}URL: $URL${NC}"
if [ -n "$OUTPUT_FILE" ]; then
    echo -e "${YELLOW}Output: $OUTPUT_FILE${NC}"
fi
echo ""

# Execute download
eval $ARIA2_CMD

if [ $? -eq 0 ]; then
    echo -e "\n${GREEN}✓ Download completed successfully!${NC}"
else
    echo -e "\n${RED}✗ Download failed!${NC}"
    exit 1
fi
