#!/bin/bash
#
# Load a bunch of demo scripts to local bin folder
# This script was only tested with Oracle Enterprise Linux
# Usage:
# curl -skL https://standby.cloud/download/samples/dl-extra.bash | bash
#

# Find executable bash library and source it
lib=`which lib.bash 2>/dev/null | sed 's|^no 'lib.bash' in .*||'`
if [ "$lib" != "" ]; then
	source "$lib"
else
	progdir=`dirname "$0"`
	if [ -r "${progdir}/lib.bash" ]; then
		source "${progdir}/lib.bash"
	else
		echo "Unexpected error: Unable to locate bash library 'lib.bash'."
		exit 1
	fi
fi

downloadurl="https://standby.cloud/download"
scriptsurl="${downloadurl}/scripts"
scriptstarget="${HOME}/bin"
extralisturl="${downloadurl}/lists/extra.txt"
manurl="${downloadurl}/man"
extralist="/tmp/extra.txt"
tool="transfer"

resstr=`which "$tool" 2>/dev/null | sed 's|^no '$tool' in .*||'`
if [ "$resstr" = "" ]; then
	echo "Please install Basic Scripts first from '$downloadurl'."
else
	mantarget="${HOME}/.local/share/man"
	if [ ! -d "${mantarget}/man1" ]; then
		mkdir -p "${mantarget}/man1"
	fi

	if [ ! -d "$scriptstarget" ]; then
		mkdir -p $scriptstarget
	fi
	transfer $extralisturl --export $extralist

	while IFS=$'\t' read -r scriptname scriptversion; do
		transfer ${scriptsurl}/${scriptname}/${scriptversion}/${scriptname} --export ${scriptstarget}/${scriptname}
		transfer ${manurl}/${scriptname}/${scriptversion}/${scriptname}.1 --export ${mantarget}/man1/${scriptname}.1
	done < <(cat $extralist | tailfromline2 | stripcomment)

	chmod 755 ${scriptstarget}/*
	gzip -f ${mantarget}/man1/*.1
	mandb ${mantarget} >/dev/null 2>&1
	rm -f $extralist
fi

