#!/bin/sh

cmd="$1"
shift

useasp=`has-asp`

filter() {
  while read fl
  do
    if [ -f "$fl" ]
    then
      continue
    fi
    echo "$fl"
  done
}

do_download() {
  dir="$1"
  msk="$2"
  if [ "$useasp" = "true" ]
  then
    asp-ls "$dir" |
    grep "$msk" |
    filter |
    asp-cp "$dir"
  else
    ftp-ls ftp.ncbi.nlm.nih.gov "$dir" |
    grep "$msk" |
    filter |
    ftp-cp ftp.ncbi.nlm.nih.gov "$dir"
  fi
}

case "$cmd" in
  -h | -help | --help | help )
  cat <<EOF
USAGE: $0
       pmc-oa | pmc-bioc | bioconcepts | meshtree | carotene
EOF
    exit 0
    ;;
  pmc-oa | -pmc-oa )
    do_download "pub/pmc/oa_bulk" "xml.tar.gz"
    exit 0
    ;;
  pmc-bioc | -pmc-bioc )
    do_download "pub/wilbur/BioC-PMC" "xml_unicode.tar.gz"
    exit 0
    ;;
  bioconcepts | -bioconcepts )
    if [ ! -f "bioconcepts2pubtatorcentral.gz" ]
    then
      do_download "pub/lu/PubTatorCentral" "bioconcepts2pubtatorcentral.gz"
    fi
    exit 0
    ;;
  meshtree | -meshtree )
    if [ ! -f "desc2019.xml" ]
    then
      echo "desc2019.xml"
      ftp-cp "nlmpubs.nlm.nih.gov" "online/mesh/MESH_FILES/xmlmesh" "desc2019.zip"
      unzip -qq desc2019.zip
      rm desc2019.zip
      chmod og-wx desc2019.xml
      chmod u-x desc2019.xml
    fi
    if [ ! -f "meshtree.txt" ]
    then
      cat desc2019.xml |
      xtract -pattern DescriptorRecord -element "DescriptorRecord/DescriptorUI" \
        -sep "," -element TreeNumber > meshtree.txt
    fi
    if [ ! -f "meshname.txt" ]
    then
      cat desc2019.xml |
      xtract -pattern DescriptorRecord -element "DescriptorRecord/DescriptorUI" \
        -first "DescriptorName/String" > meshname.txt
    fi
    if [ ! -f "pa2019.xml" ]
    then
      echo "pa2019.xml"
      ftp-cp "nlmpubs.nlm.nih.gov" "online/mesh/MESH_FILES/xmlmesh" "pa2019.xml"
    fi

    if [ ! -f "qual2019.xml" ]
    then
      echo "qual2019.xml"
      ftp-cp "nlmpubs.nlm.nih.gov" "online/mesh/MESH_FILES/xmlmesh" "qual2019.xml"
    fi

    if [ ! -f "supp2019.xml" ]
    then
      echo "supp2019.xml"
      ftp-cp "nlmpubs.nlm.nih.gov" "online/mesh/MESH_FILES/xmlmesh" "supp2019.zip"
      unzip -qq supp2019.zip
      rm supp2019.zip
      chmod og-wx supp2019.xml
      chmod u-x supp2019.xml
    fi
    exit 0
    ;;
  carotene | -carotene )
    if [ ! -f "carotene.xml" ]
    then
      do_download "entrez/entrezdirect/samples" "carotene.xml.zip"
      unzip -qq carotene.xml.zip
      rm carotene.xml.zip
    fi
    exit 0
    ;;
  * )
    break
    ;;
esac
