emulate -RL zsh
setopt extendedglob warncreateglobal typesetsilent noshortloops

[[ "$1" = plugin ]] && \
    local type="$1" user="$2" plugin="$3" id_as="$4" dir="$5" || \
    local type="$1" url="$2" id_as="$3" dir="$4"

# FUNCTION: .z-p-patch-dl-download-file-stdout {{{
# Downloads file to stdout. Supports following backend commands:
# curl, wget, lftp, lynx. Used by snippet loading.
.z-p-patch-dl-download-file-stdout() {
    local url="$1"
    local restart="$2"

    if [[ "$restart" = "1" ]]; then
        path+=( "/usr/local/bin" )
        if (( ${+commands[curl]} )) then
            command curl -fsSL "$url" || return 1
        elif (( ${+commands[wget]} )); then
            command wget -q "$url" -O - || return 1
        elif (( ${+commands[lftp]} )); then
            command lftp -c "cat $url" || return 1
        elif (( ${+commands[lynx]} )) then
            command lynx -source "$url" || return 1
        else
            [[ "${(t)path}" != *unique* ]] && path[-1]=()
            return 2
        fi
        [[ "${(t)path}" != *unique* ]] && path[-1]=()
    else
        if type curl 2>/dev/null 1>&2; then
            command curl -fsSL "$url" || return 1
        elif type wget 2>/dev/null 1>&2; then
            command wget -q "$url" -O - || return 1
        elif type lftp 2>/dev/null 1>&2; then
            command lftp -c "cat $url" || return 1
        else
            .z-p-patch-dl-download-file-stdout "$url" "1"
            return $?
        fi
    fi

    return 0
} # }}}

if [[ -n "${ZPLG_ICE[dl]}" ]] {
    local -a dls srcdst
    dls=( "${(s.;.)ZPLG_ICE[dl]}" )

    local dl hd tl
    for dl ( $dls ) {
        srcdst=( ${(@s.->.)dl} )
        srcdst=( "${srcdst[@]//((#s)[[:space:]]##|[[:space:]]##(#e))/}" )
        
        hd="" tl=""
        [[ -n ${srcdst[2]} ]] && {
            hd="${srcdst[2]:h}"
            tl="${srcdst[2]:t}"
        } || {
            hd="."
            tl="${${srcdst[1]%%\?*}:t}"
        }

        local tdir="${${(M)hd:#/*}:-$dir/$hd}"

        # Create the destination directory
        command mkdir -p "$tdir"

        local ret=0

        .z-p-patch-dl-download-file-stdout "${srcdst[1]}" >! "$tdir/$tl" || {
            .z-p-patch-dl-download-file-stdout "${srcdst[1]}" 1 >! "$tdir/$tl" || {
                print -P -- "%F{38}patch-dl annex: %F{160}Couldn't download" \
                        "the url %F{220}${srcdst[1]}%f"
                ret=1
            }
        }

        (( !ret )) && \
            print -P -- "%F{38}patch-dl annex: %F{154}File %F{220}$tl%F{154}" \
                "downloaded correctly%f"
    }
}

if [[ -n "${ZPLG_ICE[patch]}" ]] {
}

# vim:ft=zsh:sw=4:sts=4:et
