#!/bin/sh
# ozsw-fetch - wget-compatible fetch wrapper using /opt/oz/bin/curl
# Understands: -T timeout  -c (continue)  -P dir  URL
# Used by gar.lib.mk fetch rules via WGET variable.
# Note: wget's -T is connection timeout only; we use --connect-timeout
# and leave --max-time unlimited so large files don't get cut off.

CURL=/opt/oz/bin/curl
CONNECT_TIMEOUT=30
PARTIAL_DIR=.
URL=
CONTINUE=

while [ $# -gt 0 ]; do
    case "$1" in
        -T) CONNECT_TIMEOUT="$2"; shift 2 ;;
        -T*) CONNECT_TIMEOUT="${1#-T}"; shift ;;
        -c) CONTINUE="-C -"; shift ;;
        -P) PARTIAL_DIR="$2"; shift 2 ;;
        --*) shift ;;
        -*) shift ;;
        *) URL="$1"; shift ;;
    esac
done

if [ -z "$URL" ]; then
    echo "ozsw-fetch: no URL given" >&2
    exit 1
fi

FILE=$(basename "$URL")
DEST="$PARTIAL_DIR/$FILE"

exec "$CURL" \
    --connect-timeout "$CONNECT_TIMEOUT" \
    --retry 3 \
    --retry-delay 5 \
    --location \
    --fail \
    --output "$DEST" \
    ${CONTINUE} \
    "$URL"
