#!/bin/bash
##set -euxo pipefail
script_name="${0##\/}"



BLAST_FTP="https://ftp.ncbi.nih.gov/blast/executables/LATEST"
LINUXTARBALL='\-x64\-linux\.tar\.gz$'
WINTARBALL='\-x64\-win64\.tar\.gz$'
TARBALLSIG='\-x64\-.*\.tar\.gz$'

dst_dir=

usage ()
{
	local xcode=0
	while (( $# ))
	do
		echo "Error: $1" 1<&2
		xcode=255
		shift
	done
	cat <<EOF 1>&2
Obtain the lastest blast toolkit source code

Usage:
$script_name [-d <dst_dir>] [-h]
	-d <dst_dir>:
		If specified, untar the tarball to <dst_dir>. Default to current directory
		
	-h:
		Display this message and exit
EOF
exit $xcode
}

while (( $# ))
do
	cmd="$1"
	shift
	
	case $cmd in
	-d=*)
		dst_dir="${cmd#*=}"
		;;
	-d)
		dst_dir="$1"
		shift
		;;
	-h)
		usage
		;;
	*)
		;;
	esac
		
done

excode=0

[[ -z "$dst_dir" ]] && dst_dir="."


blbins_flist=( $(curl "${BLAST_FTP}/" 2> /dev/null | sed -E -e 's/^<.*">//' -e 's/<\/a>.*$//' | egrep "$LINUXTARBALL") )

echo "blbins_flist=${blbins_flist[@]}"
ttl_files=${#blbins_flist[@]}

if [[ ttl_files -eq 0 ]]
then
	echo "Cannot find latest blast tool binaries." 1>&2
	exit 254
fi

for abinar in "${blbins_flist[@]}"
do
	pfm=$(sed -E -e 's/\.tar\.gz$//' <<<"$abinar")
	
	wget "${BLAST_FTP}/$abinar" 2> /dev/null || excode=$?
	if [[ excode -ne 0 ]]
	then
		echo "Unable to get source file ${BLAST_FTP}/$abinar" 1>&2
		exit $excode
	else
		mkdir -p -- "$dst_dir/$pfm" || excode=$?
		if [[ excode -ne 0 ]]
		then
			echo "Unable to create directory $dst_dir/$pfm" 1>&2
			exit $excode
		fi
		tar -xzf "$abinar" -C "$dst_dir/$pfm" && rm -f "$abinar"
		##create links to current directory
		find "$dst_dir/$pfm" -type f -executable \( -name "rpsblast" -o -name "rpstblastn" \) -exec ln -fst . {} +
	fi
done



