#!/usr/bin/env bds

#-------------------------------------------------------------------------------
#
# Download genome data
#
#-------------------------------------------------------------------------------

include 'downloadGenome'
include 'downloadEnsembl'
include 'downloadEnsemblBulk'
include 'downloadHumanDb'
include 'downloadMane'
include 'downloadNcbi'
include 'downloadNcbiBulk'
include 'downloadOther'
include 'downloadUcsc'

#-------------------------------------------------------------------------------
# Fetch (wget) a file to current dir
# Returns true if download command is executed
#-------------------------------------------------------------------------------
bool wget(string url) return wget(url, '', true, false, false)

bool wgetTask(string url) return wget(url, '', false, false, false)

bool wget(string url, string localPath) return wget(url, localPath, true, false, false)

bool wgetTask(string url, string localPath) return wget(url, localPath, false, false, false)

#-------------------------------------------------------------------------------
# Fetch (wget) a list of files to current dir
# Returns true if download command is executed
#-------------------------------------------------------------------------------
bool wgetTask(string[] urls) {
	oks := true
	for(string url: urls) {
		ok := wget(url, '', false, false, false)
		oks &= ok
	}
	return oks
}

#-------------------------------------------------------------------------------
# Fetch (wget) a file, provide local file path
# Returns true if download command is executed (or task created)
#-------------------------------------------------------------------------------
bool wget(string url, string localPath, bool doWait, bool canFail, bool skipRemoteCheck) {
	log("Downloading '$url'")

	canFailStr := (canFail ? '|| true' : '')

	localStr := ''
	if( !localPath.isEmpty() ) {
		if( localPath.exists() && localPath.size() > 0) {
			log("Downloading: Local file '$localPath' exists, skipping")
			return true	# Already downloaded, success
		}
		localStr = "-O '$localPath'"
	}

	if( !skipRemoteCheck && !url.exists() ) {
		log("Cannot find remote file '$url'")
		return false
	}

	if( doWait ) {
		sys $wgetCmd $localStr '$url' $canFailStr
	} else {
		task $wgetCmd $localStr '$url' $canFailStr
	} 
	return true
}
