#!/bin/bash
# 2010 Etersoft www.etersoft.ru
# Author: Vitaly Lipatov <lav@etersoft.ru>
# Public domain

which xdg-open 2>/dev/null >/dev/null && BROWSER=xdg-open

# TODO: use epm assure
# (command from perl-libwww)
which GET &>/dev/null && GET=GET || GET=false

which rsync &>/dev/null && RSYNC=rsync || GET=false

# will DOWNLOADEDNAME with real name
is_archive_name()
{
	echo "$1" | grep -q -E '\.(tar|tgz|tbz2|txz|zip|gz|bz2|xz|zst|7z)$'
}

download_url()
{
	local URL="$1"
	# Cloudflare (e.g. git.pika-os.com) can reject wget/curl's default User-Agent.
	# Use eget's browser User-Agent for downloads and URL discovery, preserving other options.
	local -x EGET_OPTIONS="${EGET_OPTIONS:+$EGET_OPTIONS }-U"

	# if has_space
	if [ "${URL/ //}" != "$URL" ] ; then
		URL="$($EPMCMD tool eget --list --latest $URL)"
		[ -n "$URL" ] || fatal "Can't find $1 tarball."
	fi

	local NAME="$(basename "$URL")"

	# TODO
	# do not download if already exists...
	#[ -r "$NAME" ] && { echo "skipping $1, already exists..."; return; }
	rm -f "$NAME"

	# NOTE: disable cert checking
	# use wget with try=1 and timeout = 30 sec
	if docmd $EPMCMD tool eget -O "$NAME" "$URL" && test -r "$NAME" ; then
		# Some sites (e.g. lttng.org) answer the browser User-Agent with an HTML
		# challenge page instead of the archive: retry with the default User-Agent.
		if is_archive_name "$NAME" && file -b --mime-type "$NAME" | grep -q '^text/html' ; then
			echo "Got an HTML page instead of $NAME, retrying without the browser User-Agent ..."
			rm -f "$NAME"
			EGET_OPTIONS="${EGET_OPTIONS% -U}" ; EGET_OPTIONS="${EGET_OPTIONS%-U}"
			docmd $EPMCMD tool eget -O "$NAME" "$URL" && test -r "$NAME" && \
				! file -b --mime-type "$NAME" | grep -q '^text/html' && DOWNLOADEDNAME="$NAME" && DOWNLOADEDURL="$URL" && return
		else
			DOWNLOADEDNAME="$NAME" && DOWNLOADEDURL="$URL" && return
		fi
	elif [ -n "$EGET_OPTIONS" ] ; then
		# Other sites (e.g. SourceForge behind Cloudflare) answer the browser
		# User-Agent with 403: retry once with the default User-Agent.
		echo "Download of $NAME failed, retrying without the browser User-Agent ..."
		rm -f "$NAME"
		EGET_OPTIONS="${EGET_OPTIONS% -U}" ; EGET_OPTIONS="${EGET_OPTIONS%-U}"
		docmd $EPMCMD tool eget -O "$NAME" "$URL" && test -r "$NAME" && \
			! { is_archive_name "$NAME" && file -b --mime-type "$NAME" | grep -q '^text/html' ; } && \
			DOWNLOADEDNAME="$NAME" && DOWNLOADEDURL="$URL" && return
	fi

	rm -f "$NAME"
	return 1
}

check_url()
{
	$GET -d "$1"
}

check_rsync()
{
	[ -n "$1" ] || return 1
	$RSYNC -n "$1" >/dev/null 2>&1
}
