#!/bin/sh
#++++++++++++++++
# Copyright:    (C) 2008-2017 UDS/CNRS
# License:       GNU General Public License
#.IDENTIFICATION vizquery
#.LANGUAGE       C-shell
#.AUTHOR         Francois Ochsenbein [CDS]
#.ENVIRONMENT    
#.KEYWORDS       
#.VERSION  1.0   07-Aug-2003
#.VERSION  1.1   01-Sep-2004: propagate the -mime=fits
#.VERSION  1.2   04-Nov-2004: -get option, default is -post
#.VERSION  1.3   15-Mar-2007: final names of vizier mirrors
#.VERSION  1.4   19-Feb-2008: Addition asu-acl
#.VERSION  1.5   24-Apr-2008: Accept conditions on command line
#.VERSION  1.6   12-May-2009: Accept any fully qualified site name
#.VERSION  1.7   07-Jul-2010: Bourne shell version
#.VERSION  1.8   30-Aug-2010: Added vot64 (votable binary encoded)
#.VERSION  1.9   06-Jun-2012: Added binfits (binary FITS tables)
#.VERSION  1.91  21-Jun-2012: Added -V (choise of VOTable version)
#.VERSION  1.92  18-Jan-2013: Accept -list from standard input
#.VERSION  1.93  22-Jan-2014: Added sites viz-old and viz-beta
#.PURPOSE        Command-line interface to query VizieR
#.COMMENTS       Should work on any Linux/Unix system having wget
#----------------

# Temporary file and cleanup
tt="/tmp/vq$$"		# temporary file
trap clean_tt 1 2 3 6
clean_tt() { test -z "$tt" || rm -f $tt ; exit 2; }

# Definitions
D_BIN=`dirname $0`
PATH=$D_BIN:$PATH
pgm=`basename $0`
tmp=/tmp/vQ$$	# Temporary File
sites='
   cds   fr vizier.u-strasbg.fr     (current version, default)
   viz-old  viz-old.u-strasbg.fr    (previous version)
   viz-beta viz-beta.u-strasbg.fr   (version in development)
   cfa   us vizier.cfa.harvard.edu  
   cadc  ca vizier.hia.nrc.ca  
   adac  jp vizier.nao.ac.jp 
   iucaa in vizier.iucaa.ernet.in 
   bejing cn data.bao.ac.cn 
   cambridge uk vizier.ast.cam.ac.uk 
   ukirt hawaii www.ukirt.jach.hawaii.edu  
   moscow ru vizier.inasan.ru '

usage='
Usage: vizquery [-mime={html|asci|vot|vot64|fits|binfits|tsv|csv|xml|acl|text}]
       [-V1.v] [-site=site] [{asu_constraints...|input_file_with_contraints}] 
  The version is 1.2 by default (votable format follows the VOTable1.2 schema)
  Constraints are given in ASU form (-list can be used for a list of targets)
      vizquery -mime=text -source=I/239/hip_main HIP=1..10 
  by default constraints are asked on standard input.
(details at:  http://cdsarc-strasbg.fr/doc/vizquery.htx '

if [ $# -lt 1 ]; then
    echo "$usage"
    echo "   Sites are:"
    echo "$sites" | cut -d'(' -f1 | awk '/^$/{next}{ \
       printf "\t%-28s", $NF; \
       for (i=1; i<NF; i++) printf " (%s)", $i; \
       print ""; \
    }'
    exit 1
fi


###
### Decide on wwwget or wget 
### (choose wwwget if program exists and no proxy in use)
###
use_www=0
test `which wwwget | wc -w` -eq 1 -a -z "$http_proxy" && use_www=1


###
### Interpret the arguments
###

cgidir="viz-bin"
vizarg=""
list=""		# list of targets or constraints
path_info=""    # Versioning
wwwarg="-post"
verbop=0	# Verbose option
input_file=1	# Default: constraints in input (file or stdin)

#set verbose
while [ $# -gt 0 ]; do
    case "$1" in

     -site=*.*)	# Fully qualified site, e.g. cdsarc.u-strasbg.fr
        site=`echo "$1" | sed 's/-site=//'`
	;;

     -site=*)	# Accept any abbreviation of known sites
	site=`echo "$sites" | cut -d'(' -f1 | awk '/^$/{next}\
	 BEGIN{split("'$1'",s, "="); site=s[2]}\
	 { for (i=1; i<=NF; i++) { \
	    if (site != $i) continue; \
	    print $NF; found++; break; \
	 }}'`
	if  test -z "$site"; then  # Bad site
	    echo "****Can't interpret $1 (unknown site)"
	    echo "    (use -help option to get the list of VizieR sites)"
	    #$0	# Program alone displays the help
	    exit 1
	fi
	;;

      -wget)
        use_www=0
	;;

      -V*)
        path_info="$path_info/$1"
	;;

      -local)	# Debugging
	cgidir="local/viz-bin"
	site="cdsarc.u-strasbg.fr"
	;;

      -v)
	verbop=1
	wwwarg="$wwwarg $1"
	;;

      -get)
	wwwarg=`echo "$wwwarg" | sed s/-post//`
	;;

      -post)
	wwwarg="$wwwarg $1"
	;;

      -mime=ht*)
	script=VizieR-4
	wwwarg="$wwwarg -m"
	;;

      -mime=asc*)
	script=VizieR-4
	vizarg="$vizarg-out.form=ascii"
	;;

      -mime=binfit*)
	script=asu-binfits
	vizarg="$vizarg$1"
	;;

      -mime=fit*)
	script=asu-fits
	vizarg="$vizarg$1"
	;;

      -mime=vo*64)
	script=votable
	vizarg="$vizarg-mime=bin64"
	;;

      -mime=vo*)
	script=votable
	;;

      -mime=bin64)
	script=votable
	vizarg="$vizarg$1"
	;;

      -mime=astro*)
	script=asu-xml
	vizarg="$vizarg-out.meta=DhuL"  # 	Add <LINK>
	;;

      -mime=xml*)
	script=asu-xml
	vizarg="$vizarg$1"
	;;

      -mime=tsv*)
	script=asu-tsv
	;;

      -mime=t[ex]*)	# text or txt
	script=asu-txt
	;;

      -mime=csv*)	# Semi-colon to separate columns
	script=asu-tsv
	vizarg="$vizarg$1"
	;;

      -mime=*acl*)	# Sky-cat version
	script=asu-acl
	;;

      -mime=*cho)	# Specify the text to separate columns
	script=/viz-bin/Echo
	;;

      -mime=*)	# Specify the text to separate columns
	script=asu-tsv
	vizarg="$vizarg$1"
	;;

      -meta*)	# ASU argument, but not a search constraint
        vizarg="$vizarg$1"
	;;

      -[lf]i[ls][te]=*=*)	# A list (file) of constraints
        input_file=0		# Input file not required
	if test -z "$list"; then
	    lcol=`echo "$1" | cut -d= -f2`
	    list=`echo "$1" | cut -d= -f3`
	    test -z "$list" && list="-"
	else
	    echo "#***A single list only is acceptable" 1>&2
	    exit 1
	fi
	;;

      -[lf]i[ls][te]=*)	# 	A list (file) of targets 
        input_file=0		# Input file not required
	if test -z "$list"; then
	    lcol="-c"
	    list=`echo "$1" | cut -d= -f2`
	    test -z "$list" && list="-"
	    vizarg="$vizarg-sort=_r"
	else
	    echo "#***A single list only is acceptable" 1>&2
	    exit 1
	fi
	;;

      -list)		# 	A list (file) of targets 
        input_file=0		# Input file not required
	lcol="-c"
	list="-"
	vizarg="$vizarg-sort=_r"
	;;

      -out*)	# ASU argument
        vizarg="$vizarg$1"
	;;

      *=*)	# Any ASU argument, assumed a search constraint
	input_file=0	# Input file not required
        vizarg="$vizarg$1"
	;;

      -h*)	# HELP
	$0	# Program alone displays the help
	exit 0
	;;

      -)	# additional arguments from stdin
        input_file=1
	break	# Terminates the while loop
	;;

    [.:\#-]*)	# Any other optional argument: for vizier
        vizarg="$vizarg$1"
	;;
	#echo "****Can't understand argument: $1"
	#$0 	# Program alone displays the help
	#exit 1

      *)
        input_file=1
	break	# Terminates the while loop

    esac
    shift
    #echo "#Remaning arguments: $*"
done
#test $# -le 0 && input_file=1
#echo "#---Remains $# args; vizarg=$vizarg"

###
### Defaults:
### * Query Site = CDS
### * Mime type  = tab-separated
###
test -z "$site"   && site="vizier.u-strasbg.fr"
test -z "$script" && script="asu-tsv"

if [ $use_www -gt 0 ]; then	# wwwget does not need a temporary file, better!
    #test $input_file -eq 0 -a -z "$list" && tt=""
    call="wwwget $wwwarg -q -i $tt http://$site/$cgidir/$script$path_info"
else
    test $verbop -eq 0 && q="-q"
    call="wget -q -O - $q --post-file=$tt http://$site/$cgidir/$script$path_info"
fi
#echo "#call=$call"

# Launch the Query 
if [ -n "$tt" ]; then
    echo "$vizarg" | tr '\7' '\12' | sed '/^$/d' > $tt
fi

(echo "#...input_file=$input_file, list=$list" 1>&2)
if [ $input_file -gt 0 ]; then	# Input in a file:
    tty -s && test $# -eq 0 && echo \
           "#---Type your input ASU parameters (terminate with Control-D)" 1>&2
    cat $* >> $tt; 
elif [ -z "$list" ]; then	# No file
    echo "#...ASU parameters being sent to vizier" 1>&2
elif [ -r $list ]; then		# Has a valid list
    echo "#...query with a list ($lcol) in file: $list" 1>&2
    ( echo "$lcol=<<====$list"; cat $list; echo "====$list") >> $tt
elif [ "$list" = "-" ]; then		# stdin
    echo "#...query with a list ($lcol): enter your targets, 1 per line" 1>&2
    ( echo "$lcol=<<====$list"; cat ; echo "====$list") >> $tt
else				# Invalid input list
    echo "#***Can't read file: $list" 1>&2
    ls -l $list
    clean_tt
    exit 1
fi

# Here only when a temporary file contains the arguments, to execute
if [ $verbop -ne 0 ]; then
   (echo "#...Executing the program:"; \
    echo "$call"; \
    echo "#...beginning of $tt (`wc -l < $tt` lines):"; \
    head $tt; \
    echo "#--------------------------------------"; \
   ) 1>&2
fi
test $verbop -gt 0 && echo "#...Launching: $call" 1>&2
$call 
rm -f $tt
