#!/bin/bash

usage () {
    echo "nohup ${0} <file list> <credentials file>"
    echo ""
    echo "egaloop will read entries from a <file list>
and start 6 processes to try to download those files to the current
directory using the credentials saved in <credentials file>. It's a 
good idea to run this script with the nohup directive"
    exit 1
}

# if a credentials file was supplied make the arg string and check that the
# file exists
if [ $# -eq 2 ]; then 
    CREDOPT="-cf ${2}"
    if [ ! -f "${2}" ]; then 
        usage
    fi
# otherwise, assume the -t (test account) option
elif [ $# -eq 1 ]; then
    CREDOPT="-t"
# if the user did not supply 1 or 2 args then display usage and exit
else
    usage
fi
# also check that the file list exits
if [ ! -f "${1}" ]; then 
    usage
fi

egaloop () {
    # loop through given indices of the file list
    STR=$1
    END=$2

    while [ $STR -le $END ]; do
        FILE=$(sed "${STR}q;d" $FLIST)
        # echo "pyega3 ${CREDOPT} fetch ${FILE}"
        pyega3 ${CREDOPT} fetch ${FILE}
        STR=$(($STR+1))
    done
}

module load pyega3/3.3.0
FLIST=$1
PROC_N=6
LINE_N=$(wc -l ${FLIST} | awk '{split($0,a," "); print a[1]}')
CHUNK=$(($LINE_N/$PROC_N))
ii=1
THIS_LINE=0
while true; do 
    # if it's the last iteration make sure to get the rest 
    # in case of rounding errors 
    if [ $ii -eq $PROC_N ]; then 
        # echo "egaloop $(($THIS_LINE+1)) $LINE_N &"
        egaloop $(($THIS_LINE+1)) $LINE_N &
        break
    fi
    # echo "egaloop $(($THIS_LINE+1)) $(($THIS_LINE+$CHUNK)) &"
    egaloop $(($THIS_LINE+1)) $(($THIS_LINE+$CHUNK)) &
    THIS_LINE=$(($THIS_LINE+$CHUNK))
    ii=$(($ii+1))
done 
