#!/bin/sh

download() {
    local try=0
    local limit=60
    local timeout=30
    while [ $try -ne $limit ]; do
        try=$((try+1))
		if ! wget --no-check-certificate "$1" ; then
            printf -- "trouble downloading %s. fix your connection.\n" "$1"
            printf -- "%d tries remaining. waiting %d seconds\n" "$((limit-try))" "$timeout"
			sleep "$timeout"
		else
			# check if archive was completety downloaded
			# busybox' wget seem to be rather buggy
			if ! tar tf "$2" >/dev/null ; then
				echo "partial download detected, retrying..."
			else
				break
			fi
		fi
	done
}

# use as: tarxf http://server/path/to/ file-1 .tar.gz [dirname]
tarxf() {
  cd "$S"
  [ -f "$2$3" ] || download "$1$2$3" "$2$3"
  rm -rf "${4:-$2}"
  tar xf "$2$3"
  cd "${4:-$2}"
}

