#!/bin/bash                                                                     

thisOS=$(uname -s)

current_cwd="$PWD"
if [ "$thisOS" = "Darwin" ]; then
    
    # Absolute path for where this script is
    CAVEAT_HOME=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
    
    cd "$CAVEAT_HOME"
fi

if [ "$thisOS" != "Darwin" ]; then
    echo "This script ($0)"
    echo "   needs to be run from outside the docker/lsb environments (but sudo as root)"
    echo "If in LSB environment:"
    echo "Doing /bin/mount --bind /proc /opt/lsb-buildenv-x86_64/proc is okay"
    echo "   but don't do /usr/sbin/chroot /opt/lsb-buildenv-x86_64\
    in the terminal this is run from"
    echo "   (and don't do the chroot step in the cron file either)."
fi

# merged mac env settings into setup-env.sh which had linux env settings
source ./setup-env.sh


cd snapshots/
echo "Looking for uploads in snapshots folder/"

# possible values for list of dirs below (edit for your build system):
# gs2-caveat
#gs2-caveat-x64
#gs2-stable
#gs2-stable-x64
#gs3-caveat
#gs3-caveat-x64
#gs3-stable
#gs3-stable-x64
#gs2-src-caveat
#gs2-src-stable
#gs3-src-caveat
#gs3-src-stable
#gs2-cd-caveat
#gs2-cd-stable
#dec-caveat
#dec-stable
#dec-caveat-x64


if [ "$thisOS" = "Darwin" ]; then
    # For Darwin, generate binaries in the bitness of the machine (64 bit despite the folder name not indicating this)
    RK_LIST="gs3-caveat gs2-caveat"
else
    # For Linux
    RK_LIST="gs3-caveat-x64 gs2-caveat-x64 gs3-src-caveat gs2-src-caveat dec-caveat-x64 gs3-caveat gs2-caveat"
fi

# edit this list to reflect which builds the current system is in charge of
#for RK in gs3-caveat-x64 gs2-caveat-x64 gs3-src-caveat gs2-src-caveat dec-caveat-x64 gs3-caveat gs2-caveat
for RK in $RK_LIST
do
    if [ -d $RK ]
    then
	# the star does tab-completion
	for DIR in $RK/from*/uploads
	do
	    if [ -d $DIR ]
	    then
		echo "*** Found uploads folder $DIR"
		pushd $DIR

		#tar -c * | ssh -J kjdon@linux-labs.cms.waikato.ac.nz -T -i ~/.ssh/upload-caveat-ed25519 nzdl-gsorg@www-internal.greenstone.org      # the old way using a jump host
		if [ "$thisOS" = "Darwin" ]; then
		    echo "Running: tar -c * | ssh -J kjdon@linux-labs.cms.waikato.ac.nz -T -i ~/.ssh/upload-caveat-ed25519 nzdl@www-internal.greenstone.org"
		    # the old way using a jump host
                    tar -c * | ssh -J kjdon@linux-labs.cms.waikato.ac.nz -T -i ~/.ssh/upload-caveat-ed25519 nzdl@www-internal.greenstone.org
		else
		    echo "Running: tar -c * | ssh -i ~/.ssh/upload-caveat-ed25519 nzdl@www-internal.greenstone.org"
		    tar -c * | ssh -i ~/.ssh/upload-caveat-ed25519 nzdl@www-internal.greenstone.org
		fi
		
		popd
	    fi
	done
    else
	echo "***  no upload found for $RK" 
		
    fi
done
		
if [ "$thisOS" = "Darwin" ]; then
    cd "$current_cwd"
fi

