#!/bin/bash
# Download all firmware archives, log progress.
# Priority 1 = Kia/Hyundai ME17.9.11 family (наша) — качается первой
# Priority 2 = Kia/Hyundai other ECUs
# Priority 3 = All other brands

set +e
DEST=~/Разработки/Прошивки/_downloads
LOG=~/Разработки/Прошивки/_logs/download.log
mkdir -p "$DEST" ~/Разработки/Прошивки/_logs

# Hard-timeout wrapper: kill a stalled command after N seconds (no `timeout` on macOS).
run_to() {
    local to=$1; shift
    "$@" &
    local p=$!
    ( sleep "$to"; kill -9 "$p" 2>/dev/null ) &
    local w=$!
    wait "$p" 2>/dev/null
    local rc=$?
    kill "$w" 2>/dev/null
    return $rc
}

LINKS=/tmp/firmware_links.txt

# Stats
TOTAL=$(grep -cE '^[0-9]\|' "$LINKS")
SUCCESS=0
FAILED=0
SKIPPED=0

echo "==== Download start $(date) ====" >> "$LOG"
echo "Total links to process: $TOTAL" >> "$LOG"

while IFS='|' read -r PRIO BRAND MODEL LABEL URL; do
    # Skip comments and blanks
    [[ -z "$PRIO" || "$PRIO" =~ ^# ]] && continue
    [[ ! "$PRIO" =~ ^[0-9]+$ ]] && continue

    SAFE="P${PRIO}_${BRAND}_${MODEL}_${LABEL}"
    SAFE=$(echo "$SAFE" | tr '/ ' '__')
    MARKER="$DEST/$SAFE.done"

    if [ -f "$MARKER" ]; then
        SKIPPED=$((SKIPPED+1))
        continue
    fi

    echo "[$(date +%H:%M:%S)] P$PRIO $LABEL — start" | tee -a "$LOG"

    # Use megadl with custom path
    cd "$DEST"
    MEGA_PROXY="${MEGA_PROXY:-socks5://127.0.0.1:12090}"
    TMPOUT="$DEST/.dl_out.$$"
    # 900s hard cap per attempt so a hung proxy connection can't block the queue for hours.
    run_to 900 megadl --proxy "$MEGA_PROXY" --path "$DEST" "$URL" > "$TMPOUT" 2>&1
    RC=$?
    # Proxy hiccup / stall fallback: clean partials, retry direct once (also capped)
    if [ $RC -ne 0 ]; then
        rm -f "$DEST"/.megatmp.* 2>/dev/null
        run_to 900 megadl --path "$DEST" "$URL" > "$TMPOUT" 2>&1
        RC=$?
    fi
    OUTPUT=$(tail -5 "$TMPOUT" 2>/dev/null); rm -f "$TMPOUT"

    if [ $RC -eq 0 ]; then
        # Find newest file in dest
        NEWFILE=$(ls -t "$DEST"/*.rar "$DEST"/*.zip "$DEST"/*.7z 2>/dev/null | head -1)
        if [ -n "$NEWFILE" ]; then
            # Rename to our SAFE label format if it's an obvious mega download
            EXT="${NEWFILE##*.}"
            TARGET="$DEST/$SAFE.$EXT"
            if [ "$NEWFILE" != "$TARGET" ] && [ ! -f "$TARGET" ]; then
                mv "$NEWFILE" "$TARGET" 2>/dev/null
            fi
        fi
        touch "$MARKER"
        SUCCESS=$((SUCCESS+1))
        echo "[$(date +%H:%M:%S)] P$PRIO $LABEL — OK" >> "$LOG"
    else
        FAILED=$((FAILED+1))
        echo "[$(date +%H:%M:%S)] P$PRIO $LABEL — FAIL rc=$RC" >> "$LOG"
        echo "$OUTPUT" | tail -3 >> "$LOG"
    fi

    # Brief pause to avoid spamming mega
    sleep 2
done < "$LINKS"

echo "==== Done $(date) ====" >> "$LOG"
echo "SUCCESS=$SUCCESS FAILED=$FAILED SKIPPED=$SKIPPED of $TOTAL" >> "$LOG"
