#!/bin/bash -e
#
# mkdownload [-getDownloadSeqs=7]
#
# create download files
#  -getDownloadSeqs=days - recreate downloads if older than this number of
#   days.
#

# errors terminate with message
set -e
trap "echo Error: $(hostname) mkdownload failed >&2; exit 1" ERR
exec </dev/null

# output root
downloadRootDir=/hive/data/outside/genbank/data/ftp

#verb='-verbose=1'
verb=''

# parse command line
downloadSeqsDays=7
while [[ $1 == -* ]] ; do
    opt=$1
    shift
    case "$opt" in
        -getDownloadSeqs=*) 
            downloadSeqsDays=$(echo "$opt" |sed -e 's/-getDownloadSeqs=//') ;;
        -*) echo "Error: invalid option $opt" >&2
            exit 1 ;;
    esac
done

if [ $# != 0 ] ; then
    echo "wrong # args: mkdownload [-getDownloadSeqs=5]" >&2
    exit 1
fi

# initialize
gbRoot=/cluster/data/genbank
cd $gbRoot
. $gbRoot/lib/gbCommon.sh

# Checking for an existing lock file, Silently exits if lock file exists
# and is less than one day old,  error if older.
gbCheckLock $gbRoot/var/mkdownload/run/mkdownload.lock

# make downloads for everything on the hgwbeta or rr
databases=$(gbGetDatabases etc/hgwbeta.dbs etc/rr.dbs)

# -maxHours limits the length of of processing so lock file gets released and 
# prevent bogus stale lock message and too many completed messages
nice gbMakeDownload $verb -maxHours=8 -getDownloadSeqs=$downloadSeqsDays -downloadRootDir=$downloadRootDir $databases
