#!/bin/sh

# Public domain notice for all NCBI EDirect scripts is located at:
# https://www.ncbi.nlm.nih.gov/books/NBK179288/#chapter6.Public_Domain_Notice

DownloadOne() {

  dir="$1"
  fl="$2"

  echo "$fl" |
  nquire -asp ftp.ncbi.nlm.nih.gov "pubmed" "$dir"

  # delete if file is present but empty
  if [ -f "$fl" ] && [ ! -s "$fl" ]
  then
    rm -f "$fl"
  fi

  # retry if no file
  if [ ! -f "$fl" ]
  then
    echo "$fl" |
    nquire -asp ftp.ncbi.nlm.nih.gov "pubmed" "$dir"
  fi

  # verify contents
  if [ -s "$fl" ]
  then
    errs=$( gunzip -c "$fl" | xtract -mixed -verify 2>&1 )
    if [ -n "$errs" ]
    then
      # delete and retry one more time
      rm -f "$fl"
      echo "$fl" |
      nquire -asp ftp.ncbi.nlm.nih.gov "pubmed" "$dir"
      if [ -s "$fl" ]
      then
        errs=$( gunzip -c "$fl" | xtract -mixed -verify 2>&1 )
        if [ -n "$errs" ]
        then
          rm -f "$fl"
          frst=$( echo "$errs" | head -n 1 )
          echo "ERROR invalid file '$fl' deleted, errors start with '$frst'" >&2
        fi
      fi
    fi
  fi
}

download() {
  dir="$1"
  nquire -lst ftp.ncbi.nlm.nih.gov "pubmed" "$dir" |
  grep -v ".md5" | grep "xml.gz" |
  skip-if-file-exists |
  while read fl
  do
    echo "$fl"
    DownloadOne "$dir" "$fl"
  done
}

if [ "$#" -eq 0 ]
then
  download "baseline"
  if [ $? -ne 0 ]
  then
    download "baseline"
  fi
  download "updatefiles"
  if [ $? -ne 0 ]
  then
    download "updatefiles"
  fi
fi

while [ "$#" -gt 0 ]
do
  sect="$1"
  shift
  download "$sect"
  if [ $? -ne 0 ]
  then
    download "$sect"
  fi
done
