#!/bin/csh
# file: adscode2tmp = download bibcode-specified paper from ADS alo remote
# last: Apr  8 2021  Rob Rutten  Deil
# site: ~/rr/bin 
# note: adscode2tmp "2019ApJ...883...57K" => /tmp/2019ApJ...883...57K.pdf
#       adscode2tmp "1991A&A...252..203R" => /tmp/1991AAp...252..203R.pdf
#       works also for recent A&A and ApJ if used at licensed site
#       doesn't work for recent MNRAS even there
#       never works for Springer anywhere, use browser LeanLibrary instead

# convert A&A into AAp
setenv BIBCODE `echo ${1} | sed -e "s|A\&A|A\%26A|"`
setenv FILECODE `echo ${BIBCODE} | sed -e "s|A\%26A|AAp|"`

# check whether already present and nonzero
if (-s /tmp/${FILECODE}.pdf) then 
  exit 
endif

# # OLD: get publication via "classic" ADS link
# wget -q -O /tmp/${BIBCODE}.pdf "http://adsabs.harvard.edu/cgi-bin/nph-data_query?bibcode=${BIBCODE}&link_type=ARTICLE&db_key=AST"

# # get publication via ADS "new"
# curl -s -L "https://ui.adsabs.harvard.edu/link_gateway/` echo ${BIBCODE}`/PUB_PDF" > /tmp/${BIBCODE}.pdf

# get publication via "classic" ADS link
#RR works for both PUB_PDF and EPRINT_PDF thanks to ADS classic>new convert 
curl -s -L "http://adsabs.harvard.edu/cgi-bin/nph-data_query?bibcode=${BIBCODE}&link_type=ARTICLE&db_key=AST" > /tmp/${BIBCODE}.pdf

# if file too small maybe due to bot suspicion, fast repeats or experiments?
setenv filesize `wc -c < /tmp/${BIBCODE}.pdf`
if ($filesize < 4000) then
  echo " ===== filesize = "$filesize
  echo " ##### too small, maybe <bot> suspicion; change to html and abort"
  mv  /tmp/${BIBCODE}.pdf /tmp/${BIBCODE}.html
  exit
endif 

## switching with older alternative wget may cause bot suspicion too
## wget -q -O /tmp/${BIBCODE}.pdf "http://ui.adsabs.harvard.edu//link_gateway/${BIBCODE}/PUB_PDF"  

# open to others
mv /tmp/${BIBCODE}.pdf /tmp/rrtemp.pdf
mv /tmp/rrtemp.pdf /tmp/${FILECODE}.pdf
chmod 666 /tmp/${FILECODE}.pdf

